首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步请求示例

异步请求示例
EN

Stack Overflow用户
提问于 2013-05-17 19:29:24
回答 2查看 21.8K关注 0票数 11
代码语言:javascript
复制
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。我找不到合适的代码。

谁给我的链接或邮政编码,适合我的代码。任何有帮助的人都会很感激。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-17 19:38:03

有几件事你可以做。

  1. 你可以使用sendAsynchronousRequest来处理回调块,
  2. 你可以使用AFNetworking库,它以异步的方式处理你所有的请求。非常易于使用和设置。

选项1的代码:

代码语言:javascript
复制
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的帖子

代码语言:javascript
复制
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];
票数 22
EN

Stack Overflow用户

发布于 2018-04-30 06:08:41

作为NSURLConnection现已弃用的sendAsynchronousRequest:queue:completionHandler:方法的替代方法,您可以使用NSURLSessiondataTaskWithRequest:completionHandler:方法:

代码语言:javascript
复制
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];
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16607883

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档