[iOS] - Web Server 제이슨 방식 처리
웹서버에서 제이슨 받아와서 처리하는 것을 자꾸만 까먹어서 간단함수로 만들어 봤습니다.
typedef void (^JsonFromServerCompletionBlock)(NSDictionary *json, NSError *error);
+(void)jsonFromURL:(NSString*)strURL block:(JsonFromServerCompletionBlock)cblock
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:strURL];
NSString *json = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
NSLog(@"\nJSON: %@ \n Error: %@", json, error);
NSDictionary *jsonDict=nil;
if(!error) {
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
NSLog(@"JSON: %@", jsonDict);
}
dispatch_async(dispatch_get_main_queue(), ^{
cblock(jsonDict, error);
});
});
[Util jsonFromURL:@"유알엘", block:^(NSDictionary *json, NSError *error) {
// 해야할 작업
NSLog(@"json %@ \n\n%@", json, error);