异步请求示例 [英] Asynchronous request example

查看:45
本文介绍了异步请求示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.它有时让我崩溃.

In my project I used sendSynchronousRequest on NSURLConnection. It gives me crash sometimes.

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

So I convert this code to AsynchronousRequest. I could not find suitable code.

有人给我适合我的代码的链接或邮政编码.任何帮助将不胜感激.

Somebody give me link or post code which suitable to my code. Any hep will be appreciated.

推荐答案

您可以做几件事.

  1. 您可以使用 sendAsynchronousRequest 并处理回调块.
  2. 您可以使用 AFNetworking 库,它以异步方式处理您的所有请求.非常易于使用和设置.
  1. You can use sendAsynchronousRequest and handle the callback block.
  2. You can use AFNetworking library, which handles all your requests in asynchronous fashion. Very easy to use and set up.

选项 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 的代码:

您可能想要下载库 &首先将其包含在您的项目中.然后执行以下操作.您可以在此处

You might want to download the library & include it in your project first. Then do the following. You can follow the post on setting up 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];

这篇关于异步请求示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆