簡體   English   中英

如何使用 Swift 將音頻文件保存到 iCloud?

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

我使用 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 是否能夠處理該對象。 有什么建議?

使用 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 對象保存在不同的森林中,並且訪問它們可能會慢一點。

這是編寫音頻文件的方法。 將其保存為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)
            }
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM