The way to use iCloud drive paperwork?

The way to use iCloud drive paperwork?


Learn to sync information and knowledge by way of a shared iCloud drive folder utilizing the most recent model of Swift programming language.

iCloud drive mission setup tutorial

Let’s begin by creating a brand new mission for iOS. You possibly can choose the only view software template, don’t fear an excessive amount of about doc primarily based apps, as a result of on this tutorial we’re not going to the touch the UIDocument class in any respect. 🤷‍♂️

The way to use iCloud drive paperwork?

Step one is to allow iCloud capabilities, which can generate a brand new entitlements file for you. Additionally you’ll should allow the iCloud software service for the app id on the Apple developer portal. You also needs to assign the iCloud container that’s going for use to retailer knowledge. Only a few clicks, however it’s important to do that manually. 💩

NOTE: You want a sound Apple Developer Program membership so as to set superior app capabilities like iCloud assist. So it’s important to pay $99/yr. #greed 🤑

iCloud

So I consider that now you’ve a correct iOS app identifier with iCloud capabilities and software companies enabled. One final step is forward, it’s important to add these few traces to your Data.plist file so as to outline the iCloud drive container (folder title) that you just’re going to make use of. Be aware that you would be able to have a number of containers for one app.

NSUbiquitousContainers

    iCloud.com.tiborbodecs.teszt
    
        NSUbiquitousContainerIsDocumentScopePublic
        
        NSUbiquitousContainerName
        Teszt
        NSUbiquitousContainerSupportedFolderLevels
        Any
    

Lastly we’re prepared to maneuver ahead with some precise coding. 💻

Information inside iCloud drive containers

Working with iCloud information utilizing Swift is comparatively simple. Mainly you simply should get the bottom URL of your iCloud drive container, and you are able to do no matter you need. 🤔 Nevertheless I’ll present you some greatest practices & methods.

First it’s important to examine in case your container folder already exists, if not it is best to create it by hand utilizing the FileManager class. I’ve additionally made a “shortcut” variable for the container base URL, so I don’t have to write down all these lengthy phrases once more. 😅

var containerUrl: URL? {
    FileManager.default.url(
        forUbiquityContainerIdentifier: nil
    )?.appendingPathComponent("Paperwork")
}
// examine for container existence
if 
    let url = self.containerUrl, 
    !FileManager.default.fileExists(
        atPath: url.path, 
        isDirectory: nil
    ) {
    do {
        strive FileManager.default.createDirectory(
            at: url, withIntermediateDirectories: true, 
            attributes: nil
        )
    }
    catch {
        print(error.localizedDescription)
    }
}

Working with paths contained in the iCloud drive container is straightforward, you may append path elements to the bottom URL and use that precise location URL as you need.

let myDocumentUrl = self.containerUrl?
    .appendingPathComponent(subDirectory)
    .appendingPathComponent(fileName)
    .appendingPathExtension(fileExtension)

Choosing present information can also be fairly simple. You should utilize the built-in doc picker class from UIKit. There are solely two catches right here. 🤦‍♂️

First one is that it is advisable present the kind of the paperwork that you just’d wish to entry. Have you ever ever heard about UTI’s? No? Possibly sure…? The factor is that it’s important to discover the correct uniform kind identifier for each file kind, as a substitute of offering an extension or mime-type or one thing generally used factor. Good one, huh? 🧠

let picker = UIDocumentPickerViewController(
    documentTypes: ["public.json"], 
    in: .open
)
picker.delegate = self
picker.modalPresentationStyle = .fullScreen
self.current(picker, animated: true, completion: nil)

The second catch is that it’s important to “unlock” the picked file earlier than you begin studying it. That may be performed by calling the startAccessingSecurityScopedResource technique. Don’t overlook to name the stopAccessingSecurityScopedResource technique, or issues are going to be out of steadiness. You don’t need that, belief me! #snap 🧤

func documentPicker(
    _ controller: UIDocumentPickerViewController, 
    didPickDocumentsAt urls: [URL]
) {
    guard
        controller.documentPickerMode == .open,
        let url = urls.first,
        url.startAccessingSecurityScopedResource()
    else {
        return
    }
    defer {
        url.stopAccessingSecurityScopedResource()
    }
    // do some work with the url
}

Every part else works as you’d anticipate. It can save you information straight into the container by way of file APIs or through the use of the UIDocumentPickerViewController occasion. Listed here are a few of the most typical api calls, that you need to use to control information.

// string
strive string.write(to: url, atomically: true, encoding: .utf8)
strive String(contentsOf: url)

// knowledge
strive knowledge.write(to: url, choices: [.atomic])
strive Knowledge(contentsOf: url)

// file supervisor
FileManager.default.copyItem(at: native, to: url)
FileManager.default.removeItem(at: url)

You possibly can learn and write any type of string, knowledge. Through the use of the FileManager you may copy, transfer, delete objects or change file attributes. All of your paperwork saved inside iCloud drive will likely be magically accessible on each machine. Clearly it’s important to be logged in together with your iCloud account, and have sufficient free storage. 💰

Debugging

For those who alter one thing in your settings you may wish to increment your construct quantity as effectively so as to notify the working system in regards to the adjustments. 💡

On the mac all of the iCloud drive information / containers are positioned below the person’s Library folder contained in the Cell Paperwork listing. You possibly can merely use the Terminal or Finder to go there and record all of the information. Professional tip: search for hidden ones as effectively! 😉

cd ~/Library/Cell Paperwork
ls -la
# ls -la|grep tiborbodecs

You may as well monitor the exercise of the CloudDocs daemon, through the use of this command:

# man brctl
brctl log --wait --shorten

The output will inform you what’s really taking place throughout the sync.

Debug

I encourage you to examine the handbook entry for the brctl command, as a result of there are a couple of extra flags that may make troubleshooting less difficult. 🤐

This text was closely impressed by Marcin Krzyzanowski’s actually outdated weblog put up. 🍺

Leave a Reply

Your email address will not be published. Required fields are marked *