Swift NSURL nil 当 运行 应用程序

Swift NSURL nil when running the application

当我 运行 应用程序 Xcode 告诉我 解包 Optional 值时意外发现 nil 在 url 但 url 不是零,有人可以帮忙吗?

这是代码

import Foundation

protocol WeatherUndergroundServiceByGeographicalDelegate{

    func setWeatherByGeographical(weather:WeatherUnderground)
}

class WeatherUndergoundServiceByGeographical{

    var delegate:WeatherUndergroundServiceByGeographicalDelegate?

    func getWeatherFromWeatherUnderground(latitude:Double, longitude:Double){

        let path = "http://api.wunderground.com/api/48675fd2f5485cff/conditions/geolookup/q/\(latitude,longitude).json"
        let url = NSURL(string: path)


        //session
        let session = NSURLSession.sharedSession()


//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Error is at here~~~~~~~~~~~~~~~~~~~~~~~~~
        let task = session.dataTaskWithURL(url!) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            let json = JSON(data: data!)
            //parsing json weather condition from weather api. using swiftyJson
            let name = json["current_observation"]["display_location"]["city"].string
            let temp = json["current_observation"]["temp_c"].double
            let windsp = json["current_observation"]["wind_mph"].double

            //prasing the weather data
            let weather = WeatherUnderground(cityName: name!, temperature: temp!, windSpeed: windsp!)

            if self.delegate != nil{
                dispatch_async(dispatch_get_main_queue(), { () -> Void in

                    self.delegate?.setWeatherByGeographical(weather)

                })
            }
        }
        task.resume()
    }


}
let path = "http://api.wunderground.com/api/48675fd2f5485cff/conditions/geolookup/q/\(latitude,longitude).json"

我想你的意思是:

let path = "http://api.wunderground.com/api/48675fd2f5485cff/conditions/geolookup/q/\(latitude),\(longitude).json"

您的路径字符串中可能有错误,试试这个:

let path = "http://api.wunderground.com/api/48675fd2f5485cff/conditions/geolookup/q/\(latitude),\(longitude).json"

原因是您在字符串中插入元组值 \(latitude,longitude),这会添加额外的 space 并使 url 字符串无效,因为 space 不是百分比 -逃脱了。 相反,您必须在每个值之间插入一个逗号:\(latitude),\(longitude)