swift - 线程 10:致命错误:在展开可选值时意外发现 nil
问题描述
我正在尝试拨打服务电话以获取用户详细信息,但是我收到此错误:
线程 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,因为它在同一代码上使用默认值初始化。
这是守卫中的代码 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()
}
}
重要的是要注意网址中有大括号,例如
http://myURL.com/getInfo/getAccountTransactions/ {accountPublicKey}
解决方案
您需要string
使用addingPercentEncoding(withAllowedCharacters:)
和对 url 中的特殊字符进行转义,CharacterSet
以便URL
可以从中创建有效对象。
在你的情况下,CharacterSet
应该是.urlQueryAllowed
像这样:
//The unescaped string
let unescaped = "http://myURL.com/getInfo/getAccountTransactions/{accountPublicKey}"
//The escaped string
let escaped = unescaped.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
//...
推荐阅读
- android - Flutterfire firebase_auth 不再起作用
- python - Python:未定义函数名称
- sql-server - 如何将 SaaS 应用程序与我们的本地 SQL Server 集成?
- apache-kafka - Kafka Streams:Kerberos 票据续订
- x86 - 如何更改 VirtualBox 为来宾操作系统模拟的 CPU 指令集,例如禁用 SSE4.2 指令集?
- c# - unity脚本无法导出
- html - 如何给字体填充?
- java - 如何将字符串转换为整数类型并从用户输入中输入双精度?
- python - 比较 Python 中两个文件的非重复文件内容格式
- python - 为什么 CoreNLP ner tagger 和 ner tagger 将分开的数字连接在一起?