使用多线程加载JSON数据



我想通过多线程加载JSON数据并将其解析到NSDictionary,之前已经使用TWRequest类为twitter提要完成了这项工作,我如何使用NSURLRequest来完成以下操作:

TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString: @"https://api.twitter.com/1/statuses/public_timeline.json?screen_name=firdous_ali86&include_entities=true"] parameters:nil requestMethod:TWRequestMethodGET];
    // Notice this is a block, it is the handler to process the response
    [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
     {
         if ([urlResponse statusCode] == 200) 
         {
             tweetCollection = [[NSMutableArray alloc] init];
             Tweet *tweet;
             NSError *error;  
             NSArray *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
         }
    }];

问题是NSURLRequest并没有实现performRequestWithHandler方法。

您可以始终创建一个委托,并让该委托在完成后回调,或者使用connection did finish loading委托方法NSURLConnection来处理twitter响应。或者最好的想法是使用ASIHTTPRequestAFNetwork框架使请求异步,然后进行JSON解析

您可以将NSURLConnection与以下方法一起使用:

+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler

i使用:

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString: @"http://my_service_url"] //2
- (void)viewDidLoad
{   
    myCollection = [[NSMutableArray alloc] init];
    [super viewDidLoad];
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: 
                        kLatestKivaLoansURL];
        NSError* error;
        NSDictionary* jsonDict = [NSJSONSerialization 
                                  JSONObjectWithData:data //1
                                  options:kNilOptions 
                                  error:&error];
        NSArray* myArray = [jsonDict objectForKey:@"response"]; //2
        NSEnumerator *myIterator = [myArray objectEnumerator];
        id anObject;
        Cast *cast;
        while( anObject = [myIterator nextObject])
        {
            cast = [[Cast alloc] init];    
            cast.castTitle = [anObject objectForKey:@"castTitle"];
            [myCollection addObject:cast];
        }
        [myTableView reloadData];
    });
}

这是我本周最受欢迎的答案。看看苹果的文档。https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i

答案就在那里。

在堆栈溢出之前,有人真的读过文档吗?

最新更新