简体   繁体   English

从NSURL转换后,NSString为null

[英]NSString is null when converted from a NSURL

I am using the Open Weather API to get live weather depending on the users location. 我正在使用Open Weather API根据用户位置获取实时天气。 I first make a variable called urllink and set it equal to the http request: 我首先创建一个名为urllink的变量,并将其设置为等于http请求:

NSString *urllink = [NSString stringWithFormat:@"api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%@", lat, lng, WEATHERAPIKEY];

Then I convert that string to a url. 然后,我将该字符串转换为url。 Convert url back to string because I need to change it to NSData object: 将url转换回字符串,因为我需要将其更改为NSData对象:

NSURL *jsonURL = [NSURL URLWithString:[self urlEncodeValue:urllink]];
NSString *jsonDataString  = [[NSString alloc]initWithContentsOfURL:jsonURL]; // error on this line
NSLog(@"This is jsonDataString:%@", jsonDataString);
NSData *jsonData = [jsonDataString dataUsingEncoding:NSUTF8StringEncoding];

The urllink variable converts perfectly to NSURL . urllink变量可以完美地转换为NSURL But when I try to convert the NSURL to NSString I get nil . 但是,当我尝试将NSURL转换为NSString ,得到nil Which in return gives me nil for NSData . 作为回报,我得到NSData nil

So why is the line: 那么为什么是这一行:

 NSString *jsonDataString  = [[NSString alloc]initWithContentsOfURL:jsonURL];

giving me nil for jsonDataString ? 给我niljsonDataString吗?

You are missing the scheme (the https:// or http:// ) in your URL. 您在URL中缺少该方案( https://http:// )。 Thus the request will fail. 因此,请求将失败。 Furthermore, you should just use URLWithString directly: 此外,您应该直接使用URLWithString

NSString *urllink = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%@", lat, lng, WEATHERAPIKEY];

NSURL *jsonURL = [NSURL URLWithString:urllink];

The problem is that you're using initWithContentsOfURL , which is (a) synchronous; 问题是您正在使用initWithContentsOfURL ,它是(a)同步的; and (b) doesn't report errors. (b)不报告错误。

You should use NSURLSession which is asynchronous and reports errors: 您应使用异步的NSURLSession并报告错误:

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:jsonURL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (data == nil || error != nil) {
        NSLog(@"error: %@", error);
        return;
    }

    NSError *parseError;
    NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
    if (responseObject) {
        NSLog(@"responseObject = %@", responseObject);
    } else {
        NSLog(@"parseError: %@", parseError);
        NSLog(@"responseString: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }
}];
[task resume];

you probably need an async, data may not yet be present 您可能需要异步,数据可能还不存在

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    // The code runs in background

    do Some Long Operation

});

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

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