Search code examples
swift

unexpectedly found nil while unwrapping an Optional value parsing json swift


I try to parse json with swift using following:

   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

When my app running i got an error on line:

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

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

But i did pass correct string. Why is that error happen?


Solution

  • Your URL string contains special characters so what you need to do is encode your URL string before making URL object from it. There is two way to encode the URL string.

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