Swift 3 - URLRequest 创建崩溃

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

崩溃错误:

fatal error: unexpectedly found nil while unwrapping an Optional value

它在 Swift 3.
之前有效 它是 NSURLRequest,它起作用了。我该怎么做才能修复它?

URL(string:"urlstring") returns 是可选的,当它的值为 nil 时,您将在下一行强制展开,您应该像这样使用 guard letif let

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

或者你可以使用 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)
                }
        }
}

如果你不做任何其他事情,那么在开始时使用 guard let 到 return。

您可以阅读 swift 基础知识和可选 here

好吧,解决方案是添加!在字符串格式中的每个变量之后,以使其成为非可选的。

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