在展开解析json swift的可选值时意外发现nil

在展开解析json swift的可选值时意外发现nil,swift,Swift,我尝试使用swift解析json,方法如下: let apiPath = "http://samples.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b1b15e88fa797225412429c1c50c122a1" func getDataWithCompletionHandler(completionHandler: (_ jsonData: JSON?) -> Void) {

我尝试使用swift解析json,方法如下:

   let apiPath = "http://samples.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b1b15e88fa797225412429c1c50c122a1"

    func getDataWithCompletionHandler(completionHandler: (_ jsonData: JSON?) -> Void) {


        let request : URLRequest = URLRequest(url: URL(string: apiPath)!)

 Alamofire.request(apiPath, method: .get)
            .responseJSON { (response) in
当我的应用程序运行时,我在线上遇到一个错误:

let request : URLRequest = URLRequest(url: URL(string: apiPath)!)
致命错误:在展开可选文件时意外发现nil 价值观

但我确实传递了正确的字符串。为什么会发生此错误?

请尝试以下代码:

Alamofire.request(“http://samples.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b1b15e88fa797225412429c1c50c122a1”, method: HTTPMethod.get, parameters:nil , encoding: URLEncoding.default, headers: nil).validate().responseJSON { (response) in
           if response.result.isSuccess
           {
        //handle response
           }
       }

您在路径q=München中输入了不正确的symbolü

替换它以更正符号u。

您的URL字符串包含特殊字符,因此您需要做的是在使用URL字符串创建URL对象之前对URL字符串进行编码。有两种方法可以对URL字符串进行编码

使用

使用


从代码中删除此行。let request:URLRequest=URLRequesturl:URLstring:apiPath!您的apiPath不是正确的urlstring@UsamaSadiq为什么?请尝试一下,您会找到json响应。@BrijeshShiroya我需要url请求。你是什么意思-删除?你能发布完整的代码吗?我的意思是用完整的括号。我只想测试一下
let apiPath = "http://samples.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b1b15e88fa797225412429c1c50c122a1"
if let encodeString = apiPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),
   let url = URL(string: encodeString) {
     print(url)
}
var urlComponent = URLComponents(string: "http://samples.openweathermap.org/data/2.5/forecast")!
let queryItems = [URLQueryItem(name: "q", value: "München,DE"), URLQueryItem(name: "appid", value: "b1b15e88fa797225412429c1c50c122a1")]
urlComponent.queryItems = queryItems
print(urlComponent.url!)