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")
}
}
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