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)
}
}
How to get NSData from image picker?
When I change the "UIImagePickerControllerReferenceURL" to "UIImagePickerControllerMediaURL" its totally worked
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
self.dismiss(animated: true, completion: nil)
videoURL = info[UIImagePickerController.InfoKey.init(rawValue: "UIImagePickerControllerMediaURL")] as? URL
}
How can I convert photo (or video) from camera to NSData?
Since ALAssetsLibrary is deprecated, you should use the Photos library. See below code example.
PHPhotoLibrary.sharedPhotoLibrary().performChanges({
let assetRequest = PHAssetChangeRequest.creationRequestForAssetFromImage(image)
}, completionHandler: { (success, error) -> Void in
if success {
//image saved to photos library.
}
})
If you need to transform the image to NSData, you could simply use (as pointed out by @if-else-switch )
UIImagePNGRepresentation(image)
Hope that helps!
Get video size after Save this video to Photo Library in iOS
You can do it in three ways
1.Use NSData length
ALAssetRepresentation *rep = [alasset defaultRepresentation];
Byte *buffer = (Byte*)malloc(rep.size);
NSError *error = nil;
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:&error];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
NSLog(@"Size of video %d",data.length);
2.Make use of ALAssetRepresentationsize
3.Worst-Case Scenario: Use the videoPathURL
that points to the saved video file, retrieve it again using ALAsset
and caliculate the size.
Swift: How to handle video and photo results from a PHPicker?
Just ask whether the item provider has an item of type UTType.movie.identifier
. If so, go ahead and load it by calling loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier)
.
Actual code:
if prov.hasItemConformingToTypeIdentifier(UTType.movie.identifier) {
self.dealWithVideo(result)
} else if prov.canLoadObject(ofClass: PHLivePhoto.self) {
self.dealWithLivePhoto(result)
} else if prov.canLoadObject(ofClass: UIImage.self) {
self.dealWithImage(result)
}
Related Topics
Unsafemutablepointer<Void> to Concrete Object Type
Memory Problems When Switching Between Scenes Spritekit
Nsdateformatter Detect 24-Hour Clock in Os X and iOS
Swiftui MACos Scroll a List with Arrow Keys While a Textfield Is Active
Need Detailed Explanation for Memoize Implementation in Swift (Wwdc 14, Session 404)
Swift Codable - Parse JSON Array Which Can Contain Different Data Type
Using a Metal Shader in Scenekit
Alamofire with Custom Parameter Encoding for Swift Application
Combining Watchconnectivity and Complications
Safari App Extension Crashes After a Few Seconds for Hello World Project
Swift String Permutations Allowing the Same Strings
Swiftui, Shadow Only for Container
Pop View Controller Using Screen Edge Pan Gesture Recogniser Not Following the Thumb
How to Send Data from iPhone to Watchkit in Os2 in Swift