2017-06-29 29 views
-1

我嘗試使用解析與SWIFT JSON如下:意外地發現零而展開的可選值解析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)!) 

fatal error: unexpectedly found nil while unwrapping an Optional value.

但我沒有通過正確的字符串。爲什麼會發生這種錯誤?

+0

刪除此行從code.let要求:的URLRequest =的URLRequest(網址:URL(字符串:apiPath)! ) –

+0

你的apiPath不是一個合適的url字符串 –

+0

@UsamaSadiq爲什麼?請嘗試一下,你會發現JSON響應。 –

回答

1

您的URL字符串包含特殊字符,因此您需要對URL字符串進行編碼,然後再對URL對象進行編碼。有兩種編碼URL字符串的方法。

  1. 使用addingPercentEncoding(withAllowedCharacters:)

    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) 
    } 
    
  2. 使用URLComponents

    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!) 
    
1

試試這個代碼:此路徑「Q =慕尼黑」

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 
      } 
     } 
1

您字符串內容不正確的符號「ü」

將其替換爲正確的符號「u」

相關問題