从网站获取数据时出错

时间:2015-06-20 16:15:43

标签: objective-c macos web-scraping request

大家好我想从这个网站检索数据:http://www.timeapi.org/utc/now我正在制作的应用程序,但是当我使用以下代码发出请求时,我总是得到null:

NSURL * timeAPI = [[NSURL alloc]initWithString:@"http://www.timeapi.org/utc/now"];

NSURLRequest * urlRequest = [[NSURLRequest alloc]initWithURL:timeAPI];

__block NSData * responseData;

[NSURLConnection sendAsynchronousRequest:urlRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if(connectionError)
    {
        NSLog(@"error fetching data");
    }
    else{
        responseData = [[NSData alloc]initWithData:data];
    }
}];

NSError* error = nil;
NSLog(@"%@, erorr:", responseData);

有人能解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

请求需要时间,并且在您的日志语句中数据尚未到达。在else子句中放入responseData的日志,即数据可用时你会看到它。

您不需要(或想要)__block声明 [[NSData alloc]initWithData:data]是不必要的,只需使用initWithData:data

示例代码:

NSURL * timeAPI = [NSURL URLWithString:@"http://www.timeapi.org/utc/now"];
NSURLRequest * urlRequest = [[NSURLRequest alloc] initWithURL:timeAPI];

[NSURLConnection sendAsynchronousRequest:urlRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if(connectionError) {
        NSLog(@"error fetching data: %@", connectionError);
    }
    else {
        NSLog(@"data: %@", data);

        NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"dataString: %@", dataString);

        // Do something with the data
    }
}];