11
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http:///];
NSURLRequest *req = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];

在我的项目中,我使用sendSynchronousRequestNSURLConnection. 它有时让我崩溃。

所以我将此代码转换为AsynchronousRequest. 我找不到合适的代码。

有人给我适合我的代码的链接或发布代码。任何 hep 将不胜感激。

4

2 回答 2

22

你可以做几件事。

  1. 您可以使用sendAsynchronousRequest和处理回调块。
  2. 您可以使用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 的代码:

您可能需要先下载该库并将其包含在您的项目中。然后执行以下操作。您可以在此处关注有关设置的帖子

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];
于 2013-05-17T11:38:02.713 回答
6

作为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];
于 2018-04-29T22:08:41.120 回答