写入 HTTP 请求中的静态字典时未捕获的豁免



我在与字典相关的 http 闭包中获得了未捕获的豁免,该字典指出存在未捕获的豁免。 当我设置断点豁免时,它指向字典。 有问题的字典在结构中声明为静态变量,并且其中已经有多个值,那么这怎么会发生呢? 这是 http 请求。

 session.dataTask(with: request){ (data, response, error) in
            if let data = data,
                let tile = UIImage(data: data),
                let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first{
                let fileName = Date().timeIntervalSince1970
                let filePath = documentsURL.appendingPathComponent(String(describing: fileName))

                Maps.tileCachePath[url] = fileName  //<- this is where the exception happens

                //make sure there is no old file and if so delete it
                if FileManager.default.fileExists(atPath: filePath.path){
                    do {
                        try FileManager.default.removeItem(at: filePath)
                    } catch{
                        print("error deleting old tile")
                    }
                }
                //now write the new file
                FileManager.default.createFile(atPath: filePath.path, contents: data, attributes: nil)
                print(filePath.path)
                //return
                result(tile, error)
            } else {
                result(nil, error)
            }

            }.resume()
这是一个

错字

取代

Maps.tileCachePath[url] = fileName

Maps.tileCachePath[url] = filePath

基本上Date().timeIntervalSince1970文件名是一个非常糟糕的主意。该数字包含被视为文件扩展名的小数秒。

使用更可靠的文件名,如格式化日期,或者至少删除秒的小数部分并添加实际的文件扩展名。

Date((.timeIntervalSince1970是一个双精度值,您可能需要一个字符串值。

最新更新