Etgar
Etgar

Reputation: 5924

Swift 3 - URLRequest creation crashes

        let url = URL(string: "\(SERVER_HOST)/post?fb_id=\(fb_user)")
        var request = URLRequest(url: url!) // Crashes here

        Alamofire.request(request)
            .responseJSON { response in
                switch response.result {
                case .failure(let error):
                    onComplete(success: false)
                case .success(let responseObject):
                    onComplete(success: true)
                }
        }

The crash error:

fatal error: unexpectedly found nil while unwrapping an Optional value

It worked before the Swift 3.
It was NSURLRequest and it worked. What can I do in order to fix it?

Upvotes: 1

Views: 3037

Answers (2)

Adnan Aftab
Adnan Aftab

Reputation: 14477

URL(string:"urlstring") returns an optional and you are force unwrapping in next line when its nil value, you should use guard let or if let like this

guard let url = URL(string: "\(SERVER_HOST)/post?fb_id=\(fb_user)") else {
   return
}
var request = URLRequest(url: url)
Alamofire.request(request)
            .responseJSON { response in
                switch response.result {
                case .failure(let error):
                    onComplete(success: false)
                case .success(let responseObject):
                    onComplete(success: true)
                }
        }

or you can use if let

if let url = URL(string: "\(SERVER_HOST)/post?fb_id=\(fb_user)") {
   var request = URLRequest(url: url!)
   // and rest of the code
   Alamofire.request(request)
            .responseJSON { response in
                switch response.result {
                case .failure(let error):
                    onComplete(success: false)
                case .success(let responseObject):
                    onComplete(success: true)
                }
        }
}

If you are not doing anything else, then use guard let to return at the start.

You can read about swift basics and optional here.

Upvotes: 2

Etgar
Etgar

Reputation: 5924

Well, the solution was to add ! after each variable in the string formatting in order to make it non-optional.

let stringUrl = "\(SERVER_HOST)...\(FBUser.id!)..."

Upvotes: 2

Related Questions