ios - UIImage(contentsOfFile :) returning nil despite file existing in caches directory

标签 ios swift uiimage mapkit

<分区>

我正在尝试在缓存目录中保存带有叠加层的 map 快照,并在它存在时检索它。但是,尽管正在创建文件,但当我尝试检索它时 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)
}

最佳答案

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

关于ios - UIImage(contentsOfFile :) returning nil despite file existing in caches directory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40642217/

相关文章:

iphone - 倾斜 iPhone 以更改 UIImage(加速计)

ios - 如何停止 Fabric 运行

苹果手机 : How to keep 3G/GPRS preferred network in presence of Wifi?

ios - 更改 Collection View 中的单个 UIButton 图像会影响多个单元格

ios - 在 Swift 4 中动态更改状态栏颜色

ios - 无法从 iPhone 文档目录位置中保存的文件重新加载 UIImage

iphone - 访问上次收到的已关闭/忽略的推送通知

javascript - iOS 12 Safari 的私有(private)/隐身模式检测

Swift:UITableView 单元格受另一个部分中的单元格影响

objective-c - iOS:创建一个较暗版本的 UIImage 并保持透明像素不变?