I want to upload an image to iCloud drive from my ios app. Upto now I have upload the images by saving them locally in iCloud drive in the device and syncing it to the iCloud. here is the code i have tried.
if (!FileManager.default.fileExists(atPath: iCloudDocumentsURL.path, isDirectory: nil)) {
do{
try FileManager.default.createDirectory(at: iCloudDocumentsURL, withIntermediateDirectories: true, attributes: nil)
}catch let error {
print(error.localizedDescription)
}
}
}
let localDocumentsURL = FileManager.default.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: .userDomainMask).last! as NSURL
let iCloudDocumentsURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.appendingPathComponent("Documents").appendingPathComponent("MyArtworks")
let image = UIImage(named: "testpoto2") as UIImage?
// get the documents directory url
// choose a name for your image
let fileName = "image6.png"
// create the destination file url to save your image
let fileURL = localDocumentsURL.appendingPathComponent(fileName)
// get your UIImage jpeg data representation and check if the destination file url already exists
if !FileManager.default.fileExists(atPath: fileURL!.path) {
do {
try UIImagePNGRepresentation(image!)!.write(to: fileURL!)
print("Image Added Successfully")
} catch {
print(error)
}
} else {
print("Image Not Added")
}
if let iCloudDocumentsURL = iCloudDocumentsURL {
var isDir:ObjCBool = false
if (FileManager.default.fileExists(atPath: iCloudDocumentsURL.path, isDirectory: &isDir)) {
do{
try FileManager.default.removeItem(at: iCloudDocumentsURL)
}catch let error {
print(error.localizedDescription)
}
}
do{
try FileManager.default.copyItem(at: localDocumentsURL as URL , to: iCloudDocumentsURL)
}catch let error {
print(error.localizedDescription)
}
}
But I need to save the images directly to the iCloud. Any suggestions are appreciated.