如何通过NSURLSession发布API?

时间:2016-08-02 13:44:40

标签: objective-c api

我有以下代码 如何解析响应?

NSError *error;

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURL *url = [NSURL URLWithString:@ "API-URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

[request setHTTPMethod:@"POST"];

NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"key", @"76658b01d08e43f65c6930933f69f1",
                         nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];    

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {       
}];

[postDataTask resume];

如何从dataTaskResponse获取响应后获取字典输出?

1 个答案:

答案 0 :(得分:1)

请尝试以下代码。

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
                                                     options:kNilOptions 
                                                       error:&error];
NSLog(@"json: %@", json);