How to Convert Video (In Gallery) to Nsdata? in Swift

How to convert video (in gallery) to NSData? in Swift

Xcode 10 • Swift 4.2 or later

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
if let url = info[.mediaURL] as? URL {
do {
try FileManager.default.moveItem(at: url, to: documentsDirectoryURL.appendingPathComponent("videoName.mov"))
print("movie saved")
} catch {
print(error)
}
}
}

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

You should use if let to unwrap your optionals. Also NSData.dataWithContentsOfMappedFile was deprecated iOS8. Try using NSData method initializer contentsOfURL:

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

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

iOS : How to convert a video PHAsset to NSData

I did it !

This is the solution :

    PHCachingImageManager().requestAVAssetForVideo(asset, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [NSObject : AnyObject]?) in
dispatch_async(dispatch_get_main_queue(), {

let asset = asset as? AVURLAsset
var data = NSData(contentsOfURL: asset.URL)
})
})

And after, you have the good NSData variable which you can use to put your video to the Cloud !



Related Topics



Leave a reply



Submit