0

我正在为学校做一个项目,我想知道如果用户提交了一些东西,是否有办法实际更新与 NSURLConnection 的连接。例如,我正在根据用户名进行 twitter 搜索,并且在加载视图时设置了默认用户名。当用户在该页面上输入不同的用户名时,我需要做什么来刷新该连接?我已经设置了所有按钮处理程序,并且我使用的代码与我的 viewDidLoad 函数中的代码相同。是否有方法调用或实际重置连接的东西?

谢谢,

大卫

4

2 回答 2

0

我附上了示例代码

// member variable 'conn'
// NSURLConnection *conn;
// @property(strong, nonatomic) NSURLConnection *conn;
-(void)viewDidLoad {
  [super viewDidLoad];
  [self sendRequest];
}
- (IBAction)sendButtonClicked {
  [self sendRequest];
}
- (void)sendRequest {
  if (self.conn) {
    [self.conn cancel];
    self.conn = nil;
  }
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.com"]];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    self.conn = conn;
    [conn start];

} 
// NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
   // append received data
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
   // error handling
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
   // using data
}
于 2013-02-25T03:34:05.363 回答
0

我认为您不能“重置”连接。您将不得不提出新的请求。在您的按钮单击方法中,只需使用新用户名进行新的请求调用。它就像浏览器中的请求一样工作,当您更改 url 中的某些参数时,浏览器会向 Web 服务器发送新请求。

看看苹果的这个例子(如果你不需要缓存部分,只需关注 URLCacheConnection.h/.m)http://developer.apple.com/library/ios/#samplecode/URLCache/Listings/Classes_URLCacheController_m.html #//apple_ref/doc/uid/DTS40008061-Classes_URLCacheController_m-DontLinkElementID_10 i

于 2013-02-25T03:36:12.287 回答