JSON异步请求

编程入门 行业动态 更新时间:2024-10-27 19:15:08
本文介绍了JSON异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用async req来获取json数据,我已经通过syncrouns进行了此操作,但是现在要求已更改,但是我无法将此代码修改为aync,因为我必须返回NSdata

i want to use async req to get json data, i am doing this by syncrouns already, but now requirement is change, but i am unable to modify this code to aync, beacuse i have to return NSdata

+ (NSString *)stringWithUrl:(NSURL *)url { // if(kShowLog) NSLog(@"%@", url); NSURL *newURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url]]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:newURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1]; // Fetch the JSON response NSData *urlData; NSURLResponse *response; NSError *error; // NSOperationQueue *opQueue; // Make synchronous request urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; return [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding]; }

推荐答案

您必须为此过程创建一个单独的线程,获取json数据的同步调用将阻塞您的主线程.

You have to create a separate thread for this process, Synchronous call of getting json data will block your main thread.

我正在更改您的代码以执行异步操作,以从Web服务获取json数据.

I'm changing your code to do asynchronous operation for getting json data from web service.

+ (void)stringWithUrl:(NSURL *)url { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul); dispatch_async(queue, ^{ // if(kShowLog) NSLog(@"%@", url); NSURL *newURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@",url]]; NSURLRequest *urlRequest = [NSURLRequest requestWithURL:newURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1]; // Fetch the JSON response NSData *urlData; NSURLResponse *response; NSError *error; // NSOperationQueue *opQueue; // Make synchronous request urlData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error]; dispatch_sync(dispatch_get_main_queue(), ^{ //Here you have to put your code, which you wanted to get executed after your data successfully retrived. //This block will get executed after your request data load to urlData. }); }); }

更多推荐

JSON异步请求

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

发布评论

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

>www.elefans.com

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