Swift 2.0 NSData(contentsOfURL) always nil in-app but the same code run well in playground

50 views Asked by At

I'm using the following code to fetch data from an online api, I use the same code in both playground and my app. But somehow the exactly same code work in playground but not working on both iOS Simulator and iOS 9b1 iPhone (the line let dataSource = NSData(contentsOfURL: NSURL(string: "http://api.openweathermap.org/data/2.5/weather?id=5375480")!) is always nil when it's running on 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
    }
}

Since I was using the same api url for my iOS 8 project with Xcode 6.3.2, i know that the url is working and there's nothing to do with API keys, therefore I have no idea what's going on.

0

There are 0 answers