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

4

我使用Swift 3和Xcode 8.3.3创建了一个记录音频文件并将其保存到应用程序文档目录的应用程序。现在我想将这些文件保存到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是否能够处理这个对象。有什么建议吗?

2个回答

4

使用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)
    }
    // 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对象不同的地方,并且访问它们可能会慢一些。


Ryan,如果这个答案对你有用,请告诉我。勾选绿色框 :) - user3069232

1
这是如果您想要保存/读取视频文件的完全相同的过程。
以下是如何编写音频文件。将其保存为CKAsset:
func save(audioURL: URL) {

    let record = CKRecord(recordType: "YourType")

    let fileURL = URL(fileURLWithPath: audioURL.path)

    let asset = CKAsset(fileURL: fileURL)

    record["audioAsset"] = asset

    CKContainer.default().publicCloudDatabase.save(record) { (record, err) in
        if let err = err {
            print(err.localizedDescription)
            return 
        }
        if let record = record { return }
        print("saved: ", record.recordID)
    }
}

以下是如何从CKAsset读取音频文件的方法:
func fetchAudioAsset(with recordID: CKRecord.ID) {

    CKContainer.default().publicCloudDatabase.fetch(withRecordID: recordID) { 
        [weak self](record, err) in

        DispatchQueue.main.async {

            if let err = err {
                print(err.localizedDescription)
                return 
            }

            if let record = record { return }

            guard let audioAsset = record["audioAsset"] as? CKAsset else { return }

            guard let audioURL = audioAsset.fileURL else { return }

            do {
        
                self?.audioPlayer = try AVAudioPlayer(contentsOf: audioURL)

            } catch {
                print(error.localizedDescription)
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接