ios - 运行应用程序时 Swift NSURL nil

标签 ios swift nsurl

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

这是代码

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"

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

关于ios - 运行应用程序时 Swift NSURL nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36059342/

相关文章:

ios - PhoneGap 和 iPhone 5 : Remove top and bottom black stripes

ios - didSelectItemAtIndexPath 在 Collection View Swift 中不起作用

regex - Swift 正则表达式 - 如何提取匹配组

swift - 快照在 Firebase 中的工作原理

objective-c - 包含正斜杠的 URL 不适用于 NSWorkSpace

c++ - 在 .mm 文件中无法识别预编译 header 中的#define

ios - Swift *.stringsdict 返回波兰值的错误键

swift - 通过相同的结构从不同的 API 获取数据?

swift - iOS 8 Swift 将用户直接从警报对话框发送到位置服务

swift - 如何将 url 添加到警报?