-1

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?

Shamas S
  • 7,507
  • 10
  • 46
  • 58
Evgeniy Kleban
  • 6,794
  • 13
  • 54
  • 107

3 Answers3

1

Try this code:

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
           }
       }
Brijesh Shiroya
  • 3,323
  • 1
  • 13
  • 20
1

You string content not correct symbol "ü" in this path "q=München".

Replace it to correct symbol "u".

Citrael
  • 542
  • 4
  • 17
1

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!)
    
Nirav D
  • 71,513
  • 12
  • 161
  • 183