尽管文件存在于缓存目录中,UIImage(contentsOfFile :)返回nil

尽管文件存在于缓存目录中,UIImage(contentsOfFile :)返回nil 

我正在尝试在缓存目录中保存带有覆盖的地图快照,并在存在时检索它。但是,尽管创建了文件,但当我尝试检索它时,UIImage(contentsOfFile :)返回nil。我已经打印了写入和读取的文件路径,它们是相同的,并通过下载容器并检查目录并且文件确实存在来验证文件是否存在。

知道这里的问题是什么吗?

let cachesDirectory: URL = {
    let urls = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
    return urls[urls.endIndex - 1]}()let mapCachesDirectory = cachesDirectory.appendingPathComponent("map-snapshots", isDirectory: true)func configureMap(data: NSSet?) {
    mapView.isZoomEnabled = false
    mapView.isScrollEnabled = false
    mapView.isUserInteractionEnabled = false

    guard let data = data as? Set<SessionData>, data.count > 0 else { return }

    activityIndicatorView.isHidden = false
    activityIndicatorView.startAnimating()

    DispatchQueue.global(qos: .userInitiated).async {
        var points = [CLLocationCoordinate2D]()
        for object in data {
            guard object.locationLatitude != 0, object.locationLatitude != 0 else { continue }
            points.append(CLLocationCoordinate2DMake(object.locationLatitude, object.locationLongitude))
        }
        DispatchQueue.main.async(execute: {
            self.createOverlay(points: points)
            self.activityIndicatorView.stopAnimating()
            self.activityIndicatorView.isHidden = true
            self.cacheMapImage(view: self.mapView)
        })
    }}func cacheMapImage(view: UIView) {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 0)
    view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
    let compositeImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()


偶然的你
浏览 1679回答 2
2回答

jeck猫

问题是您正在使用URL属性absoluteString,您应该使用path属性。absoluteString和path属性之间的区别在于absoluteString包含文件url方案(“file://”),这是它没有找到应该是它的路径的文件但它实际上是它的absoluteString的原因。

临摹微笑

atPath: self.mapCachesDirectory.absoluteString应该是atPath: self.mapCachesDirectory.path
打开App,查看更多内容
随时随地看视频慕课网APP