objective-c – 异步请求示例

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.我找不到合适的代码.

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

解决方法

有几件事你可以做.

>您可以使用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];

相关文章

对象的传值与返回说起函数,就不免要谈谈函数的参数和返回值...
从实现装饰者模式中思考C++指针和引用的选择最近在看...
关于vtordisp知多少?我相信不少人看到这篇文章,多半是来自...
那些陌生的C++关键字学过程序语言的人相信对关键字并...
命令行下的树形打印最近在处理代码分析问题时,需要将代码的...
虚函数与虚继承寻踪封装、继承、多态是面向对象语言的三大特...