简体   繁体   English

dataTaskWithRequest 问题(目标 c)

[英]issue with dataTaskWithRequest (objective c)

I´m making a little app for ios and i need to get some json data.我正在为 ios 制作一个小应用程序,我需要获取一些 json 数据。 The problem is that I don´t know how to make the request properly.问题是我不知道如何正确提出请求。 I´m trying the following code, but "response" is always nil, not sure why:我正在尝试以下代码,但“响应”始终为零,不知道为什么:

-(instancetype) initWithMatchURL:(NSString*) urlFixtureJSON {
self = [super init];
if(self)
{
    NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: urlFixtureJSON]];

    __block NSData * response = [NSData new];

    NSURLSessionConfiguration * sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
    sessionConfiguration.HTTPAdditionalHeaders = @{
                                                   @"Accept"    : @"application/json",
                                                   @"api-key"   : @"<redacted>"
                                                   };

    NSURLSession *session = [NSURLSession sessionWithConfiguration: sessionConfiguration];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:
                                  ^(NSData *dataTask, NSURLResponse *responseTask, NSError *errorTask)
    {
        response = [NSData dataWithData: dataTask];      
    }];

    [task resume];

    NSLog(@"%@", response);
    ...
}

Thanks in advance提前致谢

Response will always be nil because the code within the block is executed asynchronously (so it happens in the future after the log has been written).响应将始终为零,因为块中的代码是异步执行的(因此它会在写入日志后发生)。 If you moved the logging to below response = [...] it would work.如果您将日志记录移动到response = [...] ,它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM