我想从我的ios应用程序将图像上传到iCloud驱动器。到目前为止,我已经通过将图像本地保存在设备的iCloud驱动器中并将其同步到iCloud来上传图像。这是我尝试过的代码。
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)
}
}
但是我需要将图像直接保存到iCloud。任何建议表示赞赏。