我正在使用以下代码从在线 api 获取数据,我在操场和我的应用程序中使用相同的代码。但不知何故,完全相同的代码在操场上工作,但在 iOS 模拟器和 iOS 9b1 iPhone 上都不能工作(let dataSource = NSData(contentsOfURL: NSURL(string: "http://api.openweathermap.org/data/2.5/weather?id=5375480")!)
当它在 iOS 上运行时,这条线总是为零。)
class WeatherParser: AnyObject {
let temp: NSNumber!
let temp_max: NSNumber!
let temp_min: NSNumber!
let humidity: NSNumber!
var weather_description: String!
init() {
var temp: NSNumber! = nil
var temp_max: NSNumber! = nil
var temp_min: NSNumber! = nil
var humidity: NSNumber! = nil
var weather_description: String!
let dataSource = NSData(contentsOfURL: NSURL(string: "http://api.openweathermap.org/data/2.5/weather?id=5375480")!)
if dataSource == nil {
print("nil")
}
if dataSource != nil {
do {
let parsedObject: AnyObject? = try! NSJSONSerialization.JSONObjectWithData(dataSource!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
if parsedObject != nil {
let dataFromKey_main = parsedObject!["main"] as! NSDictionary
temp = dataFromKey_main["temp"] as! NSNumber
temp_max = dataFromKey_main["temp_max"] as! NSNumber
temp_min = dataFromKey_main["temp_min"] as! NSNumber
humidity = dataFromKey_main["humidity"] as! NSNumber
let weatherArrayFromSource = parsedObject!["weather"] as? NSArray
for dataInArray in weatherArrayFromSource! {
if let objs = dataInArray as? NSDictionary {
weather_description = objs["description"] as! String
}
}
}
}
}
self.temp = temp
self.temp_max = temp_max
self.temp_min = temp_min
self.humidity = humidity
self.weather_description = weather_description
}
}
由于我使用 Xcode 6.3.2 为我的 iOS 8 项目使用相同的 api url,我知道该 url 正在工作并且与 API 密钥无关,因此我不知道发生了什么。