如何将视频(在图库中)转换为NSData?在斯威夫特 [英] How to convert video (in gallery) to NSData? in Swift
问题描述
我在Swift imagePickerController中没有info所以我不知道如何获取url并将其转换为数据以发送到Web服务。
I just haven't "info" in Swift imagePickerController so I don't know how get url and convert it to data to send to web-service.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var videoDataURL = info[UIImagePickerControllerMediaURL] as! NSURL!
var videoFileURL = videoDataURL.filePathURL
var video = NSData.dataWithContentsOfMappedFile("\(videoDataURL)")
}
推荐答案
Xcode 8.3•Swift 3.1
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any]) {
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
if let fileURL = info[UIImagePickerControllerMediaURL] as? URL {
do {
try FileManager.default.moveItem(at: fileURL, to: documentsDirectoryURL.appendingPathComponent("videoName.mov")
print("movie saved")
} catch {
print(error)
}
}
}
Swift 2
如果让我们解开您的期权,您应该使用。此外, NSData.dataWithContentsOfMappedFile
已被弃用iOS8。尝试使用NSData方法初始化程序contentsOfURL:
You should use if let to unwrap your optionals. Also NSData.dataWithContentsOfMappedFile
was deprecated iOS8. Try using NSData method initializer contentsOfURL:
注意:您还需要更改来自 [NSObject:AnyObject]
的didFinishPickingMediaWithInfo声明到 [String:AnyObject]
Note: You need also to change the didFinishPickingMediaWithInfo declaration from [NSObject : AnyObject]
to [String : AnyObject]
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let fileURL = info[UIImagePickerControllerMediaURL] as? NSURL {
if let videoData = NSData(contentsOfURL: fileURL) {
print(videoData.length)
}
}
}
Rob提到的
数据可能非常大但不是复制文件,而是应该将文件移动到文档文件夹中,如下所示:
as mentioned by Rob the data can be really large but instead of copying the file you should move the file to the documents folder as follow:
let documentsDirectoryURL = try! NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
if let fileURL = info[UIImagePickerControllerMediaURL] as? NSURL {
do {
try NSFileManagerdefaultManager().moveItemAtURL(fileURL, toURL: documentsDirectoryURL.URLByAppendingPathComponent("videoName").URLByAppendingPathExtension("mov"))
print("movie saved")
} catch {
print(error)
}
}
这篇关于如何将视频(在图库中)转换为NSData?在斯威夫特的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!