gpt4 book ai didi

ios - 为什么 NSHTTPURLResponse 返回 nil? NSURLSession, swift 2.2

转载 作者:行者123 更新时间:2023-11-29 00:57:12 25 4
gpt4 key购买 nike

我正在尝试编写一个函数,从网络上的服务中获取 JSON,但其中一行(已注释)始终返回 nil,我不知道为什么。任何帮助表示赞赏! :) 谢谢!!

func parseJSON(long: CLLocationDegrees, lat: CLLocationDegrees) {

var longitude : String = "\(long)"
var latitude : String = "\(lat)"

longitude = longitude.substringToIndex(longitude.characters.indexOf(".")!)
latitude = latitude.substringToIndex(latitude.characters.indexOf(".")!)

print("\(latitude),\(longitude)")

let appId = "xyz" //Insert API Key
let urlString = "https://api.openweathermap.org/data/2.5/weather?lat=\(latitude)&lon=\(longitude)&units=metric&appid=\(appId)"

let requestURL: NSURL = NSURL(string: urlString)!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in

//Keeps returning nil. No idea why.
if let httpResponse = response as? NSHTTPURLResponse {

print("Success!")
let statusCode = httpResponse.statusCode

if (statusCode == 200) {
print("Everyone is fine, file downloaded successfully.")
} else {
print("STATUSCODE=\(statusCode)")
}

}
}

task.resume()

}

最佳答案

func dataTaskWithRequest(_ request: NSURLRequest,
completionHandler completionHandler: (NSData?,
NSURLResponse?,
NSError?) -> Void) -> NSURLSessionDataTask

初始方法接受一个NSURLResponse。这是请求的 URL 的响应。 NSURLResponse 可以是任何类型的响应。

NSHTTPURLResponseNSURLResponse 的子类,只有当您确定您的网络服务使用HTTP 协议(protocol)。否则,转换将始终返回 nil

此外,我发现您使用的网络服务有一些使用限制:

How to get accurate API response

1 Do not send requests more then 1 time per 10 minutes from one device/one API key. Normally the weather is not changing sofrequently.

2 Use the name of the server as api.openweathermap.org. Please neveruse the IP address of the server.

3 Call API by city ID instead of city name, city coordinates or zipcode. In this case you get precise respond exactly for your city.

4 Free account has limitation of capacity and data availability. Ifyou do not get respond from server do not try to repeat yourrequest immediately, but only after 10 min. Also we recommend to storeyour previous request data.

现在我认为您的问题可能出自那里。

关于ios - 为什么 NSHTTPURLResponse 返回 nil? NSURLSession, swift 2.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37514408/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com