Easy methods to use iCloud drive paperwork?

Easy methods 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 challenge setup tutorial

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

Capabilities

Step one is to allow iCloud capabilities, which can generate a brand new entitlements file for you. Additionally you’ll should allow the iCloud utility 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 you need to do that manually. 💩

NOTE: You want a legitimate Apple Developer Program membership in an effort to set superior app capabilities like iCloud help. So you need to pay $99/12 months. #greed 🤑

iCloud

So I imagine that now you could have a correct iOS app identifier with iCloud capabilities and utility providers enabled. One final step is forward, you need to add these few traces to your Information.plist file in an effort to outline the iCloud drive container (folder identify) that you simply’re going to make use of. Notice that you may have a number of containers for one app.

<key>NSUbiquitousContainers</key>
<dict>
    <key>iCloud.com.tiborbodecs.teszt</key>
    <dict>
        <key>NSUbiquitousContainerIsDocumentScopePublic</key>
        <true/>
        <key>NSUbiquitousContainerName</key>
        <string>Teszt</string>
        <key>NSUbiquitousContainerSupportedFolderLevels</key>
        <string>Any</string>
    </dict>
</dict>

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

Recordsdata inside iCloud drive containers

Working with iCloud information utilizing Swift is comparatively straightforward. 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 & tips.

First you need to test 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 put in writing all these lengthy phrases once more. 😅

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

Working with paths contained in the iCloud drive container is easy, you possibly can append path parts to the bottom URL and use that actual location URL as you need.

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

Choosing current information can be fairly simple. You need to use the built-in doc picker class from UIKit. There are solely two catches right here. 🤦‍♂️

First one is that you’ll want to present the kind of the paperwork that you simply’d prefer to entry. Have you ever ever heard about UTI’s? No? Perhaps sure…? The factor is that you need to discover the correct uniform kind identifier for each file kind, as an alternative of offering an extension or mime-type or one thing generally used factor. Sensible 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 you need to “unlock” the picked file earlier than you begin studying it. That may be accomplished by calling the startAccessingSecurityScopedResource methodology. Don’t neglect to name the stopAccessingSecurityScopedResource methodology, 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
}

All the things else works as you’d anticipate. It can save you information straight into the container by way of file APIs or by utilizing the UIDocumentPickerViewController occasion. Listed here are among the most typical api calls, that you need to use to govern information.

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

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

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

You may learn and write any type of string, knowledge. By utilizing the FileManager you possibly can copy, transfer, delete gadgets or change file attributes. All of your paperwork saved inside iCloud drive will probably be magically obtainable on each machine. Clearly you need to be logged in together with your iCloud account, and have sufficient free storage. 💰

Debugging

If you happen to alter one thing in your settings you may need to increment your construct quantity as nicely in an effort to notify the working system in regards to the modifications. 💡

On the mac all of the iCloud drive information / containers are positioned beneath the person’s Library folder contained in the Cellular Paperwork listing. You may merely use the Terminal or Finder to go there and checklist all of the information. Professional tip: search for hidden ones as nicely! 😉

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

You may also monitor the exercise of the CloudDocs daemon, by utilizing this command:

# man brctl
brctl log --wait --shorten

The output will let you know what’s really taking place in the course of the sync.

Debug

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

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

author avatar
roosho Senior Engineer (Technical Services)
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog. 
rooshohttps://www.roosho.com
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog. 

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here


Latest Articles

author avatar
roosho Senior Engineer (Technical Services)
I am Rakib Raihan RooSho, Jack of all IT Trades. You got it right. Good for nothing. I try a lot of things and fail more than that. That's how I learn. Whenever I succeed, I note that in my cookbook. Eventually, that became my blog.