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&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...