【发布时间】:2016-05-31 22:23:15
【问题描述】:
感谢 downloadTaskWithURL,我正在下载视频,并使用以下代码将其保存到我的画廊:
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()
}
它在我的模拟器上运行良好,但在我的 iPad 上,即使出现 print("Video is saved!");,视频也不会保存。
你知道为什么吗?
我的控制台中也出现了该消息
无法从文件创建数据(空)
【问题讨论】:
-
downloadTaskWithURL方法的completionHandler部分的文档说“您必须在您的完成处理程序返回之前移动此文件或打开它以供阅读”。现在,您似乎始终都在完成处理程序中,但也许(我在这里猜测)您在完成处理程序中调用另一个方法('performChanges')会搞砸一些事情。您能否在致电performChanges之前尝试将文件复制到另一个位置? -
我对 Swift 比较陌生,你能给我举个例子吗?
-
你需要一个 NSURL 类型的
sourceURL,这就是你的location,然后你需要一个destinationURL,你可以把location附加到它上面,也许let destination = NSURL(fileURLWithPath: location.absoluteString + "_dest")。一旦你有了,你需要一个NSFileManager类型的fileManager,就像let fileManager = NSFileManager.defaultManager()一样。然后你就可以通过说fileManager.moveItemAtURL(location, toURL: destination)来移动文件了。该方法throws所以你需要将它包装在do...try...catch中。希望这是有道理的 -
您可以在这里阅读更多关于 NSFileManager 的信息:developer.apple.com/library/ios/documentation/Cocoa/Reference/… NSHipster 的这篇文章也值得一读:nshipster.com/nsfilemanager
-
你不可能找到答案。您需要了解 absoluteString 和 path 之间的区别。如果您需要本地文件的 url,只需使用 NSURL 初始化器 fileURLWithPath(请注意,absoluteString 具有 file:// 前缀,并且在使用 NSURL fileURLWithPath 初始化器时不能包含它)
标签: ios iphone swift ipad nsurlsessiondownloadtask