使用iOS 10.x Swift 3.0
你可以将你的audioObject保存为一段数据块,或者用iCloud的术语来说,是一个asset。以下是一些基本代码,用于保存图像,但原理相同,只是一段数据块。
这里的代码比你实际需要的要多得多,但我把它留在上下文中。
func files_saveImage(imageUUID2Save: String) {
var localChanges:[CKRecord] = []
let image2updated = sharedDataAccess.image2Cloud[imageUUID2Save]
let newRecordID = CKRecordID(recordName: imageUUID2Save)
let newRecord = CKRecord(recordType: "Image", recordID: newRecordID)
let theLinkID = CKReference(recordID: sharedDataAccess.iCloudID, action: .deleteSelf)
let thePath = sharedDataAccess.fnGet(index2seek: sharedDataAccess.currentSN)
newRecord["theLink"] = theLinkID
newRecord["theImageNo"] = image2updated?.imageI as CKRecordValue?
newRecord["theImagePath"] = sharedDataAccess.fnGet(index2seek: image2updated?.imageS as! Int) as CKRecordValue?
newRecord["theUUID"] = imageUUID2Save as CKRecordValue?
let theURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(NSUUID().uuidString+".dat")
do {
try image2updated?.imageD.write(to: theURL!)
} catch let e as NSError {
print("Error! \(e)");
return
}
newRecord["theImageBlob"] = CKAsset(fileURL: URL(string: (theURL?.absoluteString)!)!)
localChanges.append(newRecord)
let records2Erase:[CKRecordID] = []
let saveRecordsOperation = CKModifyRecordsOperation(recordsToSave: localChanges, recordIDsToDelete: records2Erase)
saveRecordsOperation.savePolicy = .changedKeys
saveRecordsOperation.perRecordCompletionBlock = { record, error in
if error != nil {
print(error!.localizedDescription)
}
}
saveRecordsOperation.modifyRecordsCompletionBlock = { savedRecords, deletedRecordIDs, error in
self.theApp.isNetworkActivityIndicatorVisible = false
if error != nil {
print(error!.localizedDescription, error!)
} else {
print("ok")
}
}
saveRecordsOperation.qualityOfService = .background
privateDB.add(saveRecordsOperation)
theApp.isNetworkActivityIndicatorVisible = true
}
当你想要反向操作时,你可以使用以下代码对iCloud中的blob进行解码。
let imageAsset = record["theImageBlob"] as? CKAsset
if let _ = imageAsset {
if let data = NSData(contentsOf: (imageAsset?.fileURL)!) {
imageObject = data
}
}
显然,这个例子涉及图像数据,但你和我都知道它只是数据 :) 无论颜色如何。
唯一的注意点在于速度,我非常确定资产保存在与普通iCloud对象不同的地方,并且访问它们可能会慢一些。