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

时间:2018-04-29 06:43:14

标签: swift nsurlconnection nsurl

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

主题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}

1 个答案:

答案 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)

//...