NSURLSession 和 API

问题描述 投票:0回答:1

我对

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

我找到了一个获取天气的 API,我为天气位置创建了一个字符串,然后执行了所有 NSUrl / nsurl 请求。我的目标是输出所有内容,以便我可以看到该 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]);                                          
}];
ios objective-c xcode
1个回答
0
投票

很难从这段代码中看出,但以下一个或多个问题可能会导致您的问题:

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