#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
//1
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code executed in the background
//2
NSData* kivaData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]
];
//3
NSDictionary* json = nil;
if (kivaData) {
json = [NSJSONSerialization
JSONObjectWithData:kivaData
options:kNilOptions
error:nil];
}
//4
dispatch_async(dispatch_get_main_queue(), ^{
//code executed on the main queue
//5
[self updateUIWithDictionary: json];
});
});
}
-(void)updateUIWithDictionary:(NSDictionary*)json
{
@try {
NSString *Str= [NSString stringWithFormat:
@"%@ from %@ needs %@ %@\nYou can help by contributing as little as 25$!",
json[@"loans"][0][@"name"],
json[@"loans"][0][@"location"][@"country"],
json[@"loans"][0][@"loan_amount"],
json[@"loans"][0][@"use"],
nil];
NSLog(@"%@",Str);
}
@catch (NSException *exception)
{
NSLog(@"%@", exception.reason);
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
NOTE:
If you want to load multiple JSON url at a time is possible.It is not freeze on main view controller data retrieve background thread.
No comments:
Post a Comment