我正在尝试进行服务调用以获取用户详细信息,但出现此错误:
线程 10: fatal error :在展开可选值时意外发现 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 中有大括号,例如
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)
//...
关于swift - 线程 10 : Fatal error: Unexpectedly found nil while unwrapping an Optional value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084049/