JSON异步请求 [英] JSON async request

查看:168
本文介绍了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异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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