iCloud drive mission setup tutorial
Let’s begin by creating a brand new mission for iOS. You may choose the only view software template, don’t be concerned 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. 🤷♂️
Step one is to allow iCloud capabilities, which is able to generate a brand new entitlements file for you. Additionally you will should allow the iCloud software service for the app id on the Apple developer portal. You must also assign the iCloud container that is going for use to retailer information. Just some clicks, however you need to do that manually. 💩
You want a legitimate Apple Developer Program membership with the intention to set superior app capabilities like iCloud assist. So you need to pay $99/yr. #greed 🤑
So I consider that now you’ve got a correct iOS app identifier with iCloud capabilities and software companies enabled. One final step is forward, you need to add these few strains to your Data.plist
file with the intention to outline the iCloud drive container (folder identify) that you’ll use. Observe that you could 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 recordsdata 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. 🤔 Nonetheless I will present you some finest practices & tips.
First you need to test in case your container folder already exists, if not you need to create it by hand utilizing the FileManager class. I’ve additionally made a “shortcut” variable for the container base URL, so I haven’t got to jot down all these lengthy phrases once more. 😅
var containerUrl: URL? {
FileManager.default.url(
forUbiquityContainerIdentifier: nil
)?.appendingPathComponent("Paperwork")
}
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’ll be able to append path elements to the bottom URL and use that actual location URL as you need.
let myDocumentUrl = self.containerUrl?
.appendingPathComponent(subDirectory)
.appendingPathComponent(fileName)
.appendingPathExtension(fileExtension)
Selecting present recordsdata can also be fairly easy. You need to use the built-in doc picker class from UIKit. There are solely two catches right here. 🤦♂️
First one is that it’s worthwhile to present the kind of the paperwork that you just’d wish to entry. Have you ever ever heard about UTI‘s? No? Perhaps sure…? The factor is that you need to discover the right uniform kind identifier for each file kind, as a substitute 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 carried out by calling the startAccessingSecurityScopedResource
technique. Do not forget to name the stopAccessingSecurityScopedResource technique, or issues are going to be out of stability. You do not 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()
}
}
All the pieces else works as you’d anticipate. It can save you recordsdata instantly into the container via file APIs or through the use of the UIDocumentPickerViewController
occasion. Listed here are among the most typical api calls, that you should utilize to govern recordsdata.
attempt string.write(to: url, atomically: true, encoding: .utf8)
attempt String(contentsOf: url)
attempt information.write(to: url, choices: [.atomic])
attempt Knowledge(contentsOf: url)
FileManager.default.copyItem(at: native, to: url)
FileManager.default.removeItem(at: url)
You may learn and write any form of string, information. By utilizing the FileManager
you’ll be able to copy, transfer, delete gadgets or change file attributes. All of your paperwork saved inside iCloud drive shall be magically obtainable on each machine. Clearly you need to be logged in along 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 with the intention to notify the working system in regards to the modifications. 💡
On the mac all of the iCloud drive recordsdata / containers are situated beneath the person’s Library folder contained in the Cell Paperwork listing. You may merely use the Terminal or Finder to go there and checklist all of the recordsdata. Professional tip: search for hidden ones as nicely! 😉
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 truly occurring throughout the sync.
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. 🍺