我正在尝试进行服务调用以获取用户详细信息但是我收到此错误:
主题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,因为它在同一代码上用默认值初始化。 / p>
这个守卫的代码让:
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}
答案 0 :(得分:4)
您需要使用string
和相应的addingPercentEncoding(withAllowedCharacters:)
转义网址CharacterSet
中的特殊字符,以便可以从中创建有效的URL
对象。
在您的情况下,CharacterSet
应为.urlQueryAllowed
像这样:
//The unescaped string
let unescaped = "http://myURL.com/getInfo/getAccountTransactions/{accountPublicKey}"
//The escaped string
let escaped = unescaped.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
//...