I'm downloading a video thanks to downloadTaskWithURL and I'm saving it to my gallery with this code :
func saveVideoBis(fileStringURL:String){
print("saveVideoBis");
let url = NSURL(string: fileStringURL);
(NSURLSession.sharedSession().downloadTaskWithURL(url!) { (location:NSURL?, r:NSURLResponse?, e:NSError?) -> Void in
let mgr = NSFileManager.defaultManager()
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0];
print(documentsPath);
let destination = NSURL(string: NSString(format: "%@/%@", documentsPath, url!.lastPathComponent!) as String);
print(destination);
try? mgr.moveItemAtPath(location!.path!, toPath: destination!.path!)
PHPhotoLibrary.requestAuthorization({ (a:PHAuthorizationStatus) -> Void in
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideoAtFileURL(destination!);
}) { completed, error in
if completed {
print(error);
print("Video is saved!");
self.sendNotification();
}
}
})
}).resume()
}
It works perfectly fine on my simulator but on my iPad the video isn't saved even if the print("Video is saved!");
appears.
Do you have any idea why ?
I also have that message appearing in my console
Unable to create data from file (null)
completionHandler
part of thedownloadTaskWithURL
method says "You must move this file or open it for reading before your completionHandler returns". Now, you seem to still be inside the completion handler at all times, but maybe (and I'm guessing here) you calling another method ('performChanges') inside your completionHandler is messing something up. Could you maybe try to copy the file to another location before you callperformChanges
? – RausourceURL
of type NSURL, thats yourlocation
then you need adestinationURL
you could maybe take thelocation
and append something to it, maybelet destination = NSURL(fileURLWithPath: location.absoluteString + "_dest")
. Once you have that you need afileManager
of typeNSFileManager
, like solet fileManager = NSFileManager.defaultManager()
. And then you are ready to move the file by sayingfileManager.moveItemAtURL(location, toURL: destination)
. That methodthrows
so you need to wrap that in ado...try...catch
. Hope that makes sense – RaumoveItemAtURL
you mean? OK, what does it say then if you do a print of the error?do {try something} catch let error { print("error goes here: \(error)")}
– Rau