how to retrieve audio file from parse swift

删除回忆录丶 提交于 2019-12-02 03:54:46

问题


I have successfully saved an Audio file to Parse but am struggling to download it again. I can't work out what the block should be to go with getDataInBackgroundWithBlock. And how to actually save the file. Any help much appreciated!

let query = PFQuery(className: "wordRecordings")
query.whereKey("wordName", equalTo: "\(joinedWord)")

query.findObjectsInBackgroundWithBlock { (objects:[PFObject]?, error:NSError?) -> Void in

    if error == nil{                        
       for object in objects! {
            let audioFile = object["audioFile"] as! PFFile
            audioFile.getDataInBackgroundWithBlock{ (audioFile: NSData, error:NSError?) -> Void in // THIS BLOCK ISNT CORRECT...
               if error == nil {
               let audioFile = AudioFile(data: audioFile) // THIS WORKS FOR IMAGES BUT NOT AUDIO - HOW DO I CREATE AN AUDIO FILE
               }
              }
             }
            } else {   
               print("Error: \(error!) \(error!.userInfo)")
           }
         }

Thanks to @David below here is a working solution with path code as well.

let fileString = "\(fileName)"
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let path = documentsDirectory.URLByAppendingPathComponent(fileString)

audioFile.getDataInBackgroundWithBlock { (audioFile:NSData?, error:NSError?) -> Void in
         if error == nil {
           audioFile.writeToURL(path, atomically: true)
         } else {
         print("error with getData")
         }
  }

回答1:


Checking the official documentation it should look something like this (I don't use Swift so please bear with me):

audioFile.getDataInBackgroundWithBlock{ (audioFile: NSData?, error:NSError?) -> Void in
    if error == nil {
        let path = "path-to-your-file"
        if !audioFile.writeToFile(path, atomically: true){
            print("Error saving")
        }
    }
}

I would recommend to go through some tutorials (e.g. here) where you might get better examples of file handling in Swift.

Update

Apparently both the block's parameters have to be optionals (see here). Your result block needs to be of type (audioFile: NSData?, error: NSError?)



来源:https://stackoverflow.com/questions/34754255/how-to-retrieve-audio-file-from-parse-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!