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

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

我正在尝试拨打服务电话以获取用户详细信息,但我收到此错误:

线程 10:致命错误:在展开可选值时意外发现 nil

来自这段代码:

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

当我将代码包装在一个守卫中时,代码不会被执行,因为它发现了 nil,我不确定为什么,因为 URL 字符串永远不会为 nill,因为它使用默认值初始化在相同的代码上。

这是 guard let 中的代码:

    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 中有 curly 个括号,例如

http://myURL.com/getInfo/getAccountTransactions/{accountPublicKey}

您需要使用 addingPercentEncoding(withAllowedCharacters:) 和适当的 CharacterSet 转义 url string 中的特殊字符,以便可以创建有效的 URL 对象来自它。
在您的情况下,CharacterSet 应该是 .urlQueryAllowed

像这样:

//The unescaped string
let unescaped = "http://myURL.com/getInfo/getAccountTransactions/{accountPublicKey}"

//The escaped string
let escaped = unescaped.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

//...