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

How do I save an audio file to iCloud using Swift?

我使用 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 是否能够处理该对象。有什么建议吗?

使用 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
                    }
                }

显然这个例子再次处理图像数据,但你我都知道它的所有数据 :) 不管它是什么颜色。

这里唯一需要注意的是速度,我很确定资产与您的 运行-of-the-mill iCloud 对象保存在不同的林中,访问它们可能会稍微慢一些。

如果您想 save/read 一个 视频文件

,这就是完全相同的过程

这里是 write 音频文件的方法。将其另存为 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)
    }
}

这里是 read 来自 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)
            }
        }
    }
}