Jake
Jake

Reputation: 13753

Accessing image across multiple iOS devices

I'm letting the user choose their own background image for the app. This image is suppose to sync across devices using iCloud, but I can't get it to work. The image appears to save and is accessible to the device that saved it, but other devices can't access the image. Here's how I have everything setup:

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
}

entitlements

info plist

capabilities

Is there something I'm missing or is there something wrong with my code?

Upvotes: 0

Views: 171

Answers (0)

Related Questions