简体   繁体   English

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

The crash error: 崩溃错误:

fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:解开Optional值时意外发现nil

It worked before the Swift 3. 它在Swift 3。
It was NSURLRequest and it worked. 它是NSURLRequest,并且有效。 What can I do in order to fix it? 我该怎么做才能修复它?

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 URL(string:"urlstring")返回一个可选值,当它的nil值为URL(string:"urlstring") ,您必须在下一行强制展开,您应该使用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)
                }
        }

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. 如果您没有执行其他任何操作,请使用guard let在开始时返回。

You can read about swift basics and optional here . 您可以在此处阅读有关swift基础知识和可选内容的信息

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!)..."

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM