NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http:///];
NSURLRequest *req = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];在我的项目中,我在NSURLConnection上使用了sendSynchronousRequest。它有时会让我崩溃。
因此,我将此代码转换为AsynchronousRequest。我找不到合适的代码。
谁给我的链接或邮政编码,适合我的代码。任何有帮助的人都会很感激。
发布于 2013-05-17 19:38:03
有几件事你可以做。
sendAsynchronousRequest来处理回调块,AFNetworking库,它以异步的方式处理你所有的请求。非常易于使用和设置。选项1的代码:
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
//NSLog(@"Error,%@", [error localizedDescription]);
}
else {
//NSLog(@"%@", [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]);
}
}];选项2的代码:
您可能希望先下载该库并将其包含在您的项目中。然后执行以下操作。您可以关注设置here的帖子
NSURL *url = [NSURL URLWithString:@"http://httpbin.org/ip"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"origin"]);
} failure:nil];
[operation start];发布于 2018-04-30 06:08:41
作为NSURLConnection现已弃用的sendAsynchronousRequest:queue:completionHandler:方法的替代方法,您可以使用NSURLSession的dataTaskWithRequest:completionHandler:方法:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.example.com"]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
// Option 1 (from answer above):
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"%@", string);
// Option 2 (if getting JSON data)
NSError *jsonError = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
NSLog(@"%@", dictionary);
}
else {
NSLog(@"Error: %@", [error localizedDescription]);
}
}];
[task resume];https://stackoverflow.com/questions/16607883
复制相似问题