如何在Objective-C中使用NSUrl会话获取数据?

时间:2017-06-01 09:12:58

标签: objective-c nsurlsession

我正在尝试获取JSON数据并使用NSUrl会话解析它,但每次都变为空 - 除了我想要在表视图中显示所有数据

NSError *error;

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:@"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"text/plain" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"GET"];


    NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: @"Value", @"Key",   nil];

    NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];

    [request setHTTPBody:postData];


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


        NSLog(@"Resopnse == %@",response);

        if (response != nil) {
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

            NSLog(@"JSon dict === %@",jsonDict);
        }

    }];

    [postDataTask resume];

我可以知道我做错了还有什么其他好办法吗?

2 个答案:

答案 0 :(得分:0)

请尝试以下代码。

~^((stage|prod)-)?studio.*

答案 1 :(得分:0)

请使用以下代码。希望它能解决你的问题。

    NSString *strUrl = [NSString stringWithFormat:yourUrl];
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response,
                                               NSData *data, NSError *connectionError)
     {
         if (data.length > 0 && connectionError == nil)
         {
             NSDictionary *dicResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
             NSLog(@"%@",dicResponse);
         }
     }];