【问题标题】:Unexpectedly found nil while unwrapping an Optional value even though it has a value assigned在展开可选值时意外发现 nil,即使它已分配了值
【发布时间】:2021-05-07 03:34:48
【问题描述】:

我正在使用 Swift 从冠状病毒 API 获取 JSON。但是,当我尝试运行代码时,出现此错误。

致命错误:在展开可选值时意外发现 nil:第 22 行

我的部分代码是

override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = "https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure={%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22}"
        getData(from: url)
        // Do any additional setup after loading the view.
    }
    
    private func getData(from url: String) {
        
        let getfromurl = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in
            guard let data = data, error == nil else{
                print("Something Went Wrong")
                return
            }
            
            //Have data
            var result: Response?
            do {
                result = try JSONDecoder().decode(Response.self, from: data)
            }
            catch{
                print("failed to convert \(error.localizedDescription)")
            }
            
            guard let json = result else {
                return
            }
            
            print(json.data.date)
        })
        getfromurl.resume()
    
    }

第 22 行是:

let getfromurl = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {data, response, error in

我很困惑,因为我认为这意味着 url 没有分配任何东西,但即使调试器也认为它有。

更新:

我可以获取数据,但一旦获取数据就会出错。错误是:

无法转换 valueNotFound(Swift.Int, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys( stringValue: "newDeathsByDeathDate", intValue: nil)], debugDescription: "预期的 Int 值,但发现为 null。",underlyingError: nil))

转换失败表明它是在解码 JSON 和值时出错。

【问题讨论】:

  • 请不要整天修改问题,因为当答案涉及不再被问到的东西时,未来的读者会感到困惑。添加和“更新”部分,或者 - 如果您提出完全不同的问题(TM) - 创建一个新问题

标签: ios json swift xcode


【解决方案1】:

异常并不意味着urlnil,而是URL(string:url)nil

您需要检查url 字符串是否为有效的url:

private func getData(from url: String) {
    guard let theURL = URL(string: url) else { print ("oops"); return }
    let getfromurl = URLSession.shared.dataTask(with: theURL, completionHandler: {data, response, error in
       /* ... */
    }
}

更新

既然现在给出了 url 字符串:问题是花括号;它们在RFC1738 中被标记为不安全,应替换为%7b(打开)和%7d(关闭),因此:

let url = "https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7b%22date%22:%22date%22,%22areaName%22:%22areaName%22,%22areaCode%22:%22areaCode%22,%22newCasesByPublishDate%22:%22newCasesByPublishDate%22,%22cumCasesByPublishDate%22:%22cumCasesByPublishDate%22,%22newDeathsByDeathDate%22:%22newDeathsByDeathDate%22,%22cumDeathsByDeathDate%22:%22cumDeathsByDeathDate%22%7d"

let theUrl = URL(string: url)
print (theUrl)

这也是official API documentation中的一个例子:

curl -si 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7B%22name%22:%22areaName%22%7D'

【讨论】:

  • 所以它确实会打印 oops,这确实有帮助,但是当我在浏览器中输入 URL 时,它会将我带到该页面吗?
  • 失败的 url 字符串到底是什么?
  • 看起来“结构”参数定义不正确。它返回“无效结构”错误。
  • 好吧,我正在获取数据(至少在浏览器中);尽管如此,我不打算分析@LeoGaunt 打算查询什么,我只是尝试更正语法以创建有效的URL 实例。
  • 您应该将答案标记为“已接受”并创建一个新问题,其中包含您期望的详细信息等。我可以看看那个。
【解决方案2】:

网址编码不正确。浏览器有自己的方式来对 URL 进行编码,但 URL(string: 根本不进行任何编码。

对于这种复杂的 URL,建议使用URLComponents/URLQueryItem 创建它。 URLComponents 的好处是它代表您处理编码

let structure = """
{"date":"date","areaName":"areaName","areaCode":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeathsByDeathDate":"newDeathsByDeathDate","cumDeathsByDeathDate":"cumDeathsByDeathDate"}
"""

var components = URLComponents(string: "https://api.coronavirus.data.gov.uk")!
components.path = "/v1/data"
components.queryItems = [URLQueryItem(name: "filters", value: "areaType=nation;areaName=england"),
                         URLQueryItem(name: "structure", value: structure)]

if let url = components.url {
    print(url)
}

旁注:

从不JSONDecoder 捕获块中打印 error.localizedDescription。它只向您显示一条无意义的通用错误消息。永远print(error)

【讨论】:

  • 附注确实很有帮助,因为我遇到了一个错误,这肯定提供了更好的查找方法
  • 错误很明显:keydata的值是数组,不是字典(单个对象)
  • 是的,我确实看到了我提出的请求,然后如何让它接受一个数组而不是字典
  • Response结构中的类型用方括号括起来。
  • 提出一个新问题并展示你的结构。
【解决方案3】:

对 getData 方法进行了更改,请尝试一次

private func getData(from url: String) {
    
    guard let validUrl  = URL(string: url) else {
        return
    }
    let getfromurl = URLSession.shared.dataTask(with: validUrl, completionHandler: {data, response, error in
        guard let data = data, error == nil else{
            print("Something Went Wrong")
            return
        }
        
        //Have data
        var result: Response?
        do {
            result = try JSONDecoder().decode(Response.self, from: data)
        }
        catch{
            print("failed to convert \(error.localizedDescription)")
        }
        
        guard let json = result else {
            return
        }
        
        print(json.data.date)
    })
    getfromurl.resume()

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2016-10-18
    • 2017-04-09
    • 2018-09-22
    • 2016-06-26
    相关资源
    最近更新 更多