异步请求示例

Xco*_*ode 11 objective-c nsurlconnection

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http:///];
NSURLRequest *req = [[NSURLRequest alloc]initWithURL:url];
NSURLConnection *con = [[NSURLConnection alloc]initWithRequest:req delegate:self startImmediately:YES];
Run Code Online (Sandbox Code Playgroud)

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

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

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

Har*_*ish 20

你可以做几件事.

  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]);
  }
}];
Run Code Online (Sandbox Code Playgroud)

备选方案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];
Run Code Online (Sandbox Code Playgroud)


bde*_*dev 5

作为NSURLConnection's 现在已弃用sendAsynchronousRequest:queue:completionHandler:方法的替代方法,您可以改用NSURLSession'sdataTaskWithRequest: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];
Run Code Online (Sandbox Code Playgroud)