首页 文章

线程10:致命错误:在解包Optional值时意外发现nil

提问于
浏览
2

我正在尝试进行服务调用以获取用户详细信息但是我收到此错误:

Thread 10: Fatal error: Unexpectedly found nil while unwrapping an Optional value

从这段代码:

let urlString = "http://myURL.com/getInfo/getAccountTransactions/{accountPublicKey}"
    print(urlString)
    let requestUrl = URL(string:urlString)
    let requestURL = URLRequest(url:requestUrl!)

当我将代码包装在一个保护中时,让代码不会被执行,因为它找到了nil,我不知道为什么,因为URL字符串永远不会是nill,因为它在同一代码上使用默认值初始化 .

这个守卫的代码让:

let urlString = "http://myURL.com/getInfo/getAccountTransactions/{accountPublicKey}"
    guard let requestUrl = URL(string:urlString) else { return }
    let requestURL = URLRequest(url:requestUrl)

这整个服务调用代码:

class TransactionServiceCall : NSObject, URLSessionDelegate{

let viewResponse = ThrowResponse()

func fetchTransactions(requestObject: Transaction, completion: @escaping (Dictionary<String,Any>?) -> Void) {
    let urlString = "http://myURL.com/getInfo/getAccountTransactions/{accountPublicKey}"

    guard let requestUrl = URL(string:urlString) else { return }
    let requestURL = URLRequest(url:requestUrl)

    let searchParams = Transaction.init(publicKey: requestObject.publicKey)
    var request = requestURL
    request.httpMethod = "POST"
    request.httpBody = try?  searchParams.jsonData()
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    let session = URLSession.shared

    let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
        do {
            let httpResponse = response as! HTTPURLResponse
            let statusCode = httpResponse.statusCode

            if 200 ... 299 ~= statusCode {
                if let json = try JSONSerialization.jsonObject(with: data!) as? Dictionary<String,Any> {
                    self.viewResponse.dismissLoader()
                    print(json)
                    completion(json)
                }
            }else{
                self.viewResponse.dismissLoader()
                self.viewResponse.showFailureAlert(title: "Failure", message: "")
                completion(nil)
            }
        } catch {
            DispatchQueue.main.async {
                self.viewResponse.dismissLoader()
                self.viewResponse.showFailureAlert(title: "Failure", message: "")
                completion(nil)
            }
        }
    })

    task.resume()

  }

}

重要的是要注意url中有大括号,例如

http://myURL.com/getInfo/getAccountTransactions/

1 回答

  • 4

    您需要使用 addingPercentEncoding(withAllowedCharacters:) 和相应的 CharacterSet 来转义网址 string 中的特殊字符,以便可以从中创建有效的 URL 对象 .
    在您的情况下, CharacterSet 应为 .urlQueryAllowed

    像这样:

    //The unescaped string
    let unescaped = "http://myURL.com/getInfo/getAccountTransactions/{accountPublicKey}"
    
    //The escaped string
    let escaped = unescaped.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
    
    //...
    

相关问题