异步请求示例

编程入门 行业动态 更新时间:2024-10-27 23:22:26
本文介绍了异步请求示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"/]; 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.

推荐答案

您可以做几件事.

  • 您可以使用 sendAsynchronousRequest 并处理回调块.
  • 您可以使用 AFNetworking 库,它以异步方式处理您的所有请求.非常易于使用和设置.
  • You can use sendAsynchronousRequest and handle the callback block.
  • 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:@"httpbin/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];

    更多推荐

    异步请求示例

    本文发布于:2023-11-11 17:44:53,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1579131.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:示例

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!