【问题标题】:NSURLSession and APINSURLSession 和 API
【发布时间】:2016-03-12 04:30:01
【问题描述】:

我对 NSUrlSession 和 API 感到非常困惑。这是我第一次尝试使用 API,所以请以最简单的形式解释这一点。

我找到了一个获取天气的 API,我为天气位置创建了一个字符串。然后做了所有的 NSUrl / nsurlrequest。我的目标是输出所有内容,以便我可以看到该 API 的密钥。这是我到目前为止所拥有的,但它显示的只是“程序以退出代码 0 结束”

我真的不知道 NSUrlsession 期间发生了什么,因为我通过 youtube 视频了解了如何将 API 与 NSUrlConnection 一起使用。

 NSString *location = @"London";

    NSString *weatherString = [NSString stringWithFormat:@"https://api.openweathermap.org/data/2.5/weather?q=%@", location];
    NSURL *weatherURL = [NSURL URLWithString:weatherString];

    NSURLRequest *request = [NSURLRequest requestWithURL:weatherURL];

    NSURLSession *session = [NSURLSession sharedSession];



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

                                  NSDictionary *weatherDictionary = [NSJSONSerialization JSONObjectWithData:data
                                                                                                        options:NSJSONReadingMutableContainers
                                                                                                              error:nil];
 NSLog(@"%@", [weatherDictionary description]);                                          
}];

【问题讨论】:

标签: objective-c iphone xcode api


【解决方案1】:

从这个 sn-p 很难判断,但以下一个或多个问题可能会导致您的问题:

  1. 您在某处保留对该任务的引用,对吗?
  2. dataTaskWithRequest 的文档中,您需要调用 [task resume] 才能真正启动任务。
  3. 该 URL 不起作用,因为 api.openweathermap.org 站点不支持 HTTPS。您需要将其更改为 http,并可能在应用的 Info.plist 中添加一个例外以允许非安全连接(新应用默认禁用它们)。
  4. 解决所有问题后,您需要一个 API 密钥才能使请求真正成功。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 2015-11-20
    • 2016-09-18
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多