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.它有时候让我崩溃
解决方法
有几件事你可以做.
>您可以使用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];