Reputation: 4652
I want to load JSON data through multithreading and parse it to NSDictionary, have done it previously using TWRequest class for twitter feeds, How can I use NSURLRequest to do the same as:
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];
}
}];
problem is that NSURLRequest doesnt implement performRequestWithHandler method.
Upvotes: 0
Views: 1380
Reputation: 4652
i used:
#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];
});
}
Upvotes: 0
Reputation: 973
You can use NSURLConnection
with the method:
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
Upvotes: 1
Reputation: 11452
you can always create a delegate and let that delegate to call back after completion, Or use connection did finish loading delegate method of NSURLConnection
to process twitter response. Or the best idea is to use ASIHTTPRequest
or AFNetwork
framework to make request async and then do JSON
parsing
Upvotes: 1
Reputation: 3703
Here is my most popular answer of the week. Look at Apple's docs. https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i
The answer is right in there.
Does anyone actually read the documentation before coming to stack overflow?
Upvotes: -1