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

Etgar
  • 5,774
  • 2
  • 16
  • 30
  • What is `SERVER_HOST`, what is `fb_user`, what is `url` (probably `nil`) - what is the assembled string? You might want to split the url creation into two statements, one for creating the string, one for passing the entire string to `URL(...)`. – luk2302 Jun 18 '16 at 17:18
  • 3
    For example, does `SERVER_POST` include scheme (`http://` or `https://`). Also, what is `fb_user`? Could it be an optional (which would cause problems unless you unwrap it)? Do either `SERVER_POST` or `fb_user` have any any reserved characters (e.g. space)? Share the full URL string with us. – Rob Jun 18 '16 at 17:27
  • @Rob You right, thanks a lot! Swift 3 makes the \(fb_user) to be optional. – Etgar Jun 18 '16 at 17:32

2 Answers2

2

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.

Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63
Adnan Aftab
  • 14,377
  • 4
  • 45
  • 54
2

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!)..."
Etgar
  • 5,774
  • 2
  • 16
  • 30