在我的应用程序中,我想使用NSURLConnection
类。那么请告诉我如何使用这个?这包含很多委托方法,请告诉我如何使用它们?
答案 0 :(得分:12)
使用
启动连接self.responseData = [NSMutableData data];
NSURL *url = [NSURL URLWithString:@"http://sampleurl/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection autorelease];
您可以在connectionDidFinishLoading委托方法
中捕获响应#pragma mark - NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"Connection failed: %@", [error description]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//Getting your response string
NSString *responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
}
针对您的内存泄漏问题
在接口文件
中声明响应数据NSMutableData *_responseData;
财产如下
@property (nonatomic, retain) NSMutableData *responseData;
并合成它
@synthesize responseData = _responseData;
不要在任何地方发布它(我们使用方便的构造函数进行分配)。我们已经在connectionDidFinishLoading方法中将其设置为nil。
答案 1 :(得分:4)
在iOS 5和OS X 10.7或更高版本中,您可以使用以下方法异步加载数据:
NSURL *url = [NSURL URLWithString:@"http://sampleurl/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue]
completionHandler: ^(NSURLResponse * response, NSData * data, NSError * error) {
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse*)response;
if(httpResponse.statusCode == 200) {
//your code to handle the data
}
}
];
或者,如果您想同步执行此操作(如果您要加载大数据,则不建议这样做会挂起应用程序)(在OS X 10.2+和iOS 2.0 +中可用)
NSURL *url = [NSURL URLWithString:@"http://sampleurl/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLResponse * response;
NSError * error;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];