首页 > 解决方案 > 跨多个 iOS 设备访问图像

问题描述

我让用户为应用选择自己的背景图片。此图像假设使用 iCloud 跨设备同步,但我无法让它工作。图像似乎已保存,保存它的设备可以访问,但其他设备无法访问该图像。这是我进行所有设置的方式:

static func setBackgroundImage(image: UIImage?) {
    if let image = image {
        let notification = Notification(name: updatedBackgroundImageNotificationName, object: nil, userInfo: ["image": image])
        NotificationCenter.default.post(notification)
    } else {
        NotificationCenter.default.post(name: updatedBackgroundImageNotificationName, object: nil)
    }

    guard let directoryUrl = CloudSettings.resourcesDirectoryUrl,
        let fileUrl = CloudSettings.backgroundImageUrl else {
        print("Unable to save background")
        return
    }

    var isDirectory = ObjCBool(true)
    if !FileManager.default.fileExists(atPath: directoryUrl.path, isDirectory: &isDirectory) {
        do {
            try FileManager.default.createDirectory(at: directoryUrl, withIntermediateDirectories: true, attributes: nil)
        } catch let error {
            print(error)
            return
        }
    }

    let stop = fileUrl.startAccessingSecurityScopedResource()

    defer {
        if stop {
            fileUrl.stopAccessingSecurityScopedResource()
        }
    }

    isDirectory = ObjCBool(false)
    if FileManager.default.fileExists(atPath: fileUrl.path, isDirectory: &isDirectory) {
        do {
            try FileManager.default.removeItem(at: fileUrl)
        } catch let error {
            print(error)
            return
        }
    }

    if let imageData = image?.pngData() {
        do {
            try imageData.write(to: fileUrl)
        } catch let error {
            print(error)
            return
        }
    }
}

static func getBackgroundImage() -> UIImage? {
    guard let url = CloudSettings.backgroundImageUrl else {
        print("Unable to get background image")
        return nil
    }

    let stop = url.startAccessingSecurityScopedResource()

    defer {
        if stop {
            url.stopAccessingSecurityScopedResource()
        }
    }

    var isDirectory = ObjCBool(false)
    if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory) {
        return UIImage(contentsOfFile: url.path)
    }

    return nil
}

权利

信息列表

能力

是我遗漏了什么还是我的代码有问题?

标签: iosswifticloudcloudkitubiquitycontainer

解决方案


推荐阅读