一尘不染

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

swift

我正在尝试将具有叠加层的地图快照保存在caches目录中,并在其存在时进行检索。但是,尽管正在创建文件,但当我尝试检索它时,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()

    DispatchQueue.global(qos: .userInitiated).async {
        if let compositeImage = compositeImage, let info = self.info {
            let data = UIImagePNGRepresentation(compositeImage)
            do {
                var isDirectory: ObjCBool = false
                let fileManager = FileManager.default
                if fileManager.fileExists(atPath: self.mapCachesDirectory.absoluteString, isDirectory: &isDirectory) == false {
                    try fileManager.createDirectory(at: self.mapCachesDirectory, withIntermediateDirectories: true, attributes: nil)
                }
                let fileURL = self.mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png")
                try data?.write(to: fileURL)
                print("\(fileURL.absoluteString) Saved")
            } catch {
                log.error(error)
            }
        }
    }
}

func cachedMapImage() -> UIImage? {
    guard let info = info else { return nil }
    let filePath = mapCachesDirectory.appendingPathComponent(info.uid).appendingPathExtension("png").absoluteString
    let image = UIImage(contentsOfFile: filePath)
    print("\(filePath): \(image)")
    return image
}

func createOverlay(points: [CLLocationCoordinate2D]) {
    guard points.count > 0 else { return }

    let overlay = MKGeodesicPolyline(coordinates: points, count: points.count)
    mapView.add(overlay)

    let inset: CGFloat = 50.0
    mapView.setVisibleMapRect(overlay.boundingMapRect, edgePadding: UIEdgeInsetsMake(inset,inset,inset,inset), animated: true)
}

阅读 489

收藏
2020-07-07

共1个答案

一尘不染

那里的问题是您使用URL属性absoluteString,而应该使用path属性。absoluteStringpath属性之间的区别在于,absoluteString包含文件url方案(“file://”),这是它未能在应该作为其路径的文件中找到文件的原因,而实际上是其absoluteString。

2020-07-07