NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http:///]; NSURLRequest *req = [[NSURLRequest alloc]initWithURL:url]; NSURLConnection *con = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];@H_502_4@在我的项目中,我在NSURLConnection上使用了sendSynchronousRequest.它有时候让我崩溃 @H_502_4@所以我把这个代码转换成AsynchronousRequest.我找不到合适的代码. @H_502_4@有人给我链接或适合我的代码的代码.任何肝将不胜感激.
解决方法
有几件事你可以做.
@H_502_4@>您可以使用sendAsynchronousRequest并处理回调块.
>您可以使用AFNetworking库,它以异步方式处理所有请求.非常易于使用和设置. @H_502_4@选项1的代码:
>您可以使用AFNetworking库,它以异步方式处理所有请求.非常易于使用和设置. @H_502_4@选项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]); } }];@H_502_4@选项2的代码: @H_502_4@你可能想下载图书馆&首先将其包含在您的项目中.然后执行以下操作.您可以按照设置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];