如何使用Swift将音频文件保存到iCloud?

时间:2017-08-09 17:31:24

标签: ios swift xcode icloud cloudkit

我使用Swift 3和Xcode 8.3.3创建了一个应用程序,用于记录音频文件并将其保存到应用程序的Document目录中。我现在想将这些文件保存到iCloud以备份它们。我已经能够使用以下代码将简单记录保存到iCloud:

let database = CKContainer.default().publicCloudDatabase

func saveToCloud(myContent: String){
    let myRecord = CKRecord(recordType: "AudioRecording")
    myRecord.setValue(myContent, forKey: "content")
    database.save(myRecord) { (record, error) in
        print(error ??  "No error")
        guard record != nil else {return}
        print("Saved record to iCloud")
    }
}

似乎我只需要添加一行看起来像这样的代码:

newNote.setValue(audioObject, forKey: "Audio")

但是我不确定我需要将哪个对象传递给audioObject并且iCloud是否能够处理该对象。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

使用iOS 10.x Swift 3.0

您可以将audioObject保存为一团数据;或者在iCloud说话,一种资产。这里有一些保存图像的基本代码,但它是相同的原理,只是一团数据。

这里的代码比你真正需要的要多得多,但我把它留在了上下文中。

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)
    }
    // deal with conflicts
    // set completionHandler of wrapper operation if it's the case
    }
    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对象不同的森林中,访问它们可能会慢得多。