我正在swift上编写一个iOS应用程序,它从URL下载视频并将其写入磁盘。我正在获取数据,但到目前为止,写入磁盘并不成功。以下是代码:
let yourURL = NSURL(string: "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_10mb.mp4")
//Create a URL request
let urlRequest = NSURLRequest(URL: yourURL!)
//get the data
var theData = NSData();
do{
theData = try NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil)
}
catch let err as NSError
{
}
try! PHPhotoLibrary.sharedPhotoLibrary().performChangesAndWait({ ()-> Void in
if #available(iOS 9.0, *) {
PHAssetCreationRequest.creationRequestForAsset().addResourceWithType(PHAssetResourceType.Video, data: theData, options: nil)
print("SUCESS");
} else {
};
});
我收到以下错误,有任何见解:
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=-1 "(null)": file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-703.0.18.1/src/swift/stdlib/public/core/ErrorType.swift, line 54
答案 0 :(得分:0)
一个问题是您尝试将视频(可能非常大)加载到NSURLSession
的内存中。如果您可以在持久存储中传输和传输文件,那就好了。您可以使用NSURLConnection
下载任务而不是使用已弃用的sendSynchronousRequest
方法NSURLSession
来完成此操作。
通过使用NSURLSession
下载任务,您可以避免尝试同时在内存中保存大型视频,而是将视频直接传输到持久存储。 (注意,不要使用sendSynchronousRequest
数据任务,因为它与NSURLConnection
的弃用方法NSURLSession
具有相同的内存占用问题。)
一旦addResourceWithType
下载任务将下载直接流式传输到持久存储,您就可以将文件移动到临时文件,然后使用NSData
,再次提供文件URL而不是{ {1}}。
当我这样做(并添加一些其他有用的错误检查)时,它似乎工作正常:
// make sure it's authorized
PHPhotoLibrary.requestAuthorization { authorizationStatus in
guard authorizationStatus == .Authorized else {
print("cannot proceed without permission")
return
}
self.downloadVideo()
}
其中:
func downloadVideo() {
let fileManager = NSFileManager.defaultManager()
// create request
let url = NSURL(string: "http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_10mb.mp4")!
let task = NSURLSession.sharedSession().downloadTaskWithURL(url) { location, response, error in
// make sure there weren't any fundamental networking errors
guard location != nil && error == nil else {
print(error)
return
}
// make sure there weren't and web server errors
guard let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200 else {
print(response)
return
}
// move the file to temporary folder
let fileURL = NSURL(fileURLWithPath: NSTemporaryDirectory())
.URLByAppendingPathComponent(url.lastPathComponent!)
do {
try fileManager.moveItemAtURL(location!, toURL: fileURL)
} catch {
print(error)
return
}
// now save it in our photo library
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
PHAssetCreationRequest.creationRequestForAsset().addResourceWithType(.Video, fileURL: fileURL, options: nil)
}, completionHandler: { success, error in
defer {
do {
try fileManager.removeItemAtURL(fileURL)
} catch let removeError {
print(removeError)
}
}
guard success && error == nil else {
print(error)
return
}
print("SUCCESS")
})
}
task.resume()
}
注意,因为NSURLSession
对于确保您不会执行不安全的请求更为严格,您可能需要更新info.plist
(右键单击它并选择"打开作为" - "源代码")并将其添加到文件中:
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>sample-videos.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
但是,当我完成所有这些操作后,视频已下载并成功添加到我的照片库中。请注意,我在这里删除了所有同步请求(NSURLSession
是异步的,因为performChanges
),因为您几乎从不想执行同步请求(当然也不会在主队列上)。