Get Image Filename using UIImagePickerController - ios

I am trying (AND FAILING) to get the user to upload an image and then pass the image name and actual image to another controller. This worked fine on a simulator and an actual device before ios11. But now, it just works on the simulator and crashes every time on the actual device. I am using TestFlight to test this so I am unable to see the errors on the device. But I saw this and was able to create my method which looks like this:
#objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
if #available(iOS 9.0, *) {
let url = info[UIImagePickerControllerReferenceURL] as! URL
//let assets = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
//imageName = PHAssetResource.assetResources(for: assets.firstObject!).first!.originalFilename
let result = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil)
imageName = PHAssetResource.assetResources(for: result.firstObject!).first!.originalFilename
// let asset = result.firstObject
// if(asset == nil){
// print("asset is NIL")
// }else {
// print("asset is not NIL")
// }
// print(asset?.value(forKey: "filename"))
// iconImageName = asset?.value(forKey: "filename") as! String
print("FILENAME START")
print(iconImageName)
print("FILENAME END")
} else {
// Fallback on earlier versions
}
self.dismiss(animated: true, completion: { () -> Void in
})
}
the commented out code are other ways I tried to get the file name. Why does this work on a simulator but not on a real device? I have looked online but this seems like the right way except it is not.
PS: Long story but my device does not work when connected to my Mac, which is why I am using TestFlight.

You can get fileName from UIImagePicker easily by this way:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let imageURL = info[UIImagePickerControllerReferenceURL] as? URL {
let result = PHAsset.fetchAssets(withALAssetURLs: [imageURL], options: nil)
let asset = result.firstObject
print(asset?.value(forKey: "filename"))
}
dismiss(animated: true, completion: nil)
}
For further information, you can follow this answer: https://stackoverflow.com/a/40628457/5167909

I believe you can get the image path(and from there the filename easily) from the info dictionary:
info[UIImagePickerControllerImageURL]

Try this:
PHAsset *asset = [self assetFromDictionary:info];
if (asset) {
NSData *fileData = nil;
NSString *fileName = [self filenameForAsset:asset];
}
- (PHAsset *)assetFromDictionary:(NSDictionary *)info {
PHAsset *asset = nil;
if (#available(iOS 11.0, *)) {
NSURL *assetURL = info[UIImagePickerControllerImageURL];
if (assetURL) {
asset = [info valueForKey:UIImagePickerControllerPHAsset];
}
} else {
NSURL *assetURL = info[UIImagePickerControllerReferenceURL];
if (assetURL) {
asset = [[PHAsset fetchAssetsWithALAssetURLs:#[assetURL] options:nil] lastObject];
}
}
return asset;
}
- (NSString *)filenameForAsset:(PHAsset *)asset {
NSString *filename = #"";
if (#available(iOS 9.0, *)) {
filename = [[PHAssetResource assetResourcesForAsset:asset] firstObject].originalFilename;
} else {
filename = [asset valueForKey:#"filename"];
}
return filename;
}

Related

Swift 4 didFinishPickingMediaWithInfo save image

I am using UIImagePickerController to use my camera like so:
#objc func toggle() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
//Define UIImagePickerController variable
let imagePicker = UIImagePickerController()
//Assign the delegate
imagePicker.delegate = self
//Set image picker source type
imagePicker.sourceType = .camera
//Allow Photo Editing
imagePicker.allowsEditing = true
//Present camera
UIApplication.topViewController()?.present(imagePicker, animated: true, completion: nil)
}
}
Now I am trying to capture the image taken using the didFinishPickingMediaWithInfo method, I got this example online:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let imageUrl = info[UIImagePickerControllerOriginalImage] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)
do
{
try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
}
catch
{
// Catch exception here and act accordingly
}
UIApplication.topViewController()?.dismiss(animated: true, completion: nil);
}
But I changed UIImagePickerControllerReferenceURL to UIImagePickerControllerOriginalImage as UIImagePickerControllerReferenceURL is nil. but after I change that I get this fatal error:
Could not cast value of type 'UIImage' (0x1b6b02b58) to 'NSURL'
How do I save the image take from the camera? What am I doing wrong?
Write your code as following this will give you image.
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
UIImagePickerControllerOriginalImage return image not NSURL
Write following code to get image url in iOS 11. From iOS 11 UIImagePickerControllerImageURL is available, earlier there are UIImagePickerControllerMediaURL key to get image url.
if #available(iOS 11.0, *) {
if let imageURL = info[UIImagePickerControllerImageURL] as? URL {
print(imageURL)
}
} else {
if let imageUrl = info[UIImagePickerControllerMediaURL] as? URL {
print(imageUrl)
}
}
I hope this will help you.
The one who are searching for complete method to implement for Swift 4.2+
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage{
imageView.image = pickedImage
}
imgPicker.dismiss(animated: true, completion: nil)
}
This will return you the original image according to new syntax
For Image URL and Media URL, Use the respective
let imgURL = info[UIImagePickerController.InfoKey.imageURL]
let mediaURL = info[UIImagePickerController.InfoKey.mediaURL]

UIImagePickerControllerOriginalImage is not working in ios 11.2.1

In what cases will I be sad? if I have set allowEditing as false.
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
// I am happy :)
} else {
// I am sad :(
}
dismiss(animated: true, completion: nil)
}
(I got a crash in iOS 11.2.1 iPhone SE(as per Crashlytics), so confused if there are legit conditions where this can fail or it is just an iOS bug.)
changed in IOS 12
image.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
I've read it in a Apple Developer Forum thread that, if the image size is larger (Above 2048 X 2048) on iOS 11 UIImagePickerControllerOriginalImage returns nil. As a work-around the post suggests to use Photos framework to get the picked image. The solution offered in that post is as follows:
Objective C:
__block UIImage *image = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
if (#available(iOS 11.0, *))
{
PHAsset * asset = (PHAsset*)[info objectForKey:UIImagePickerControllerPHAsset];
PHImageManager *manager = [PHImageManager defaultManager];
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
requestOptions.synchronous = true;
[manager requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeDefault options:requestOptions resultHandler:^void(UIImage *img, NSDictionary *info) {
if(img != nil)
{
image = img;
}
}];
}
Reference : iOS 11 does not return the original image for large images with UIImagePickerControllerOriginalImage
Swift:
var image = info[UIImagePickerControllerOriginalImage]
if #available(iOS 11.0, *)
{
let asset = info[UIImagePickerControllerPHAsset] as! PHAsset
let manager = PHImageManager.default()
let requestOptions = PHImageRequestOptions()
requestOptions.resizeMode = PHImageRequestOptionsResizeMode.exact
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryMode.highQualityFormat
requestOptions.isSynchronous = true
manager.requestImage(for: asset, targetSize: PHImageManagerMaximumSize, contentMode: PHImageContentMode.default, options: requestOptions, resultHandler: { (img, info) in
if img != nil
{
image = img
}
})
}
the method signature has changed like so:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
guard let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else {
fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
}
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismiss(animated: true, completion: nil)
}
Note the second argument:
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]
It is not an array of strings like in the previous method signature.
I ended up using this:
import Photos
extension UIImage {
static func from(info: [String : Any]) -> UIImage? {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
return image
}
var imageToBeReturned: UIImage?
if let url = info[UIImagePickerControllerReferenceURL] as? URL,
let asset = PHAsset.fetchAssets(withALAssetURLs: [url], options: nil).firstObject {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
option.isSynchronous = true
manager.requestImage(for: asset, targetSize: CGSize(width: 1000, height: 1000), contentMode: .aspectFit, options: option, resultHandler: {(image: UIImage?, info: [AnyHashable : Any]?) in
imageToBeReturned = image
})
}
return imageToBeReturned
}
}
In this way-
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let selectedImage = UIImage.from(info: info) {
// I am happy :)
} else {
// I am sad :(
}
dismiss(animated: true, completion: nil)
}
This is working for me, please do suggest any improvements :)

How to Get Video from a Live Photo in iOS

I'm trying to figure it out, but can't find any useful information.
I only found this:
PHAssetResourceManager.defaultManager().writeDataForAssetResource(assetRes,
toFile: fileURL, options: nil, completionHandler:
{
// Video file has been written to path specified via fileURL
}
but I'm ashamed to say I have no idea how to play it out.
I've created a UIImagePickerController and loaded an Image from the Camera Roll.
Use this code to get the video from live photo:
- (void)videoUrlForLivePhotoAsset:(PHAsset*)asset withCompletionBlock:(void (^)(NSURL* url))completionBlock{
if([asset isKindOfClass:[PHAsset class]]){
NSString* identifier = [(PHAsset*)asset localIdentifier];
NSString* filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.mov",[NSString stringWithFormat:#"%.0f",[[NSDate date] timeIntervalSince1970]]]];
NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
PHLivePhotoRequestOptions* options = [PHLivePhotoRequestOptions new];
options.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
options.networkAccessAllowed = YES;
[[PHImageManager defaultManager] requestLivePhotoForAsset:asset targetSize:[UIScreen mainScreen].bounds.size contentMode:PHImageContentModeDefault options:options resultHandler:^(PHLivePhoto * _Nullable livePhoto, NSDictionary * _Nullable info) {
if(livePhoto){
NSArray* assetResources = [PHAssetResource assetResourcesForLivePhoto:livePhoto];
PHAssetResource* videoResource = nil;
for(PHAssetResource* resource in assetResources){
if (resource.type == PHAssetResourceTypePairedVideo) {
videoResource = resource;
break;
}
}
if(videoResource){
[[PHAssetResourceManager defaultManager] writeDataForAssetResource:videoResource toFile:fileUrl options:nil completionHandler:^(NSError * _Nullable error) {
if(!error){
completionBlock(fileUrl);
}else{
completionBlock(nil);
}
}];
}else{
completionBlock(nil);
}
}else{
completionBlock(nil);
}
}];
}else{
completionBlock(nil);
}
}
Basically what you have to do is that you first need to fetch the PHLivePhoto object from your PHAsset. After that, you will have to traverse all the asset resources within your live photo and check if it is of type PHAssetResourceTypePairedVideo.
If yes, you got your video. Now you will require to save it to some temporary directory as I did here and use this file for whatever purpose you may have.
To Play this video, you can use the following code:
NSURL *videoURL = [NSURL fileURLWithPath:fileUrl];
AVPlayer *player = [AVPlayer playerWithURL:videoURL];
AVPlayerViewController *playerViewController = [AVPlayerViewController new];
playerViewController.player = player;
[self presentViewController:playerViewController animated:YES completion:nil];
Feel free to ask if you need any clarification.
P.S.- I made a few changes in this method to remove dependency of my application's code so the above code is untested, however I feel it should work as expected.
Swift 4 version
import Photos
import MobileCoreServices
// <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
#IBAction func showImagePicker(sender: UIButton) {
let picker = UIImagePickerController()
picker.delegate = self;
picker.allowsEditing = false;
picker.sourceType = .photoLibrary;
picker.mediaTypes = [kUTTypeLivePhoto as String, kUTTypeImage as String];
present(picker, animated: true, completion: nil);
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard
let livePhoto = info[UIImagePickerControllerLivePhoto] as? PHLivePhoto,
let photoDir = generateFolderForLivePhotoResources()
else {
return;
}
let assetResources = PHAssetResource.assetResources(for: livePhoto)
for resource in assetResources {
// SAVE FROM BUFFER
// let buffer = NSMutableData()
// PHAssetResourceManager.default().requestData(for: resource, options: nil, dataReceivedHandler: { (chunk) in
// buffer.append(chunk)
// }, completionHandler: {[weak self] error in
// self?.saveAssetResource(resource: resource, inDirectory: photoDir, buffer: buffer, maybeError: error)
// })
// SAVE DIRECTLY
saveAssetResource(resource: resource, inDirectory: photoDir, buffer: nil, maybeError: nil)
}
picker.dismiss(animated: true) {}
}
func saveAssetResource(
resource: PHAssetResource,
inDirectory: NSURL,
buffer: NSMutableData?, maybeError: Error?
) -> Void {
guard maybeError == nil else {
print("Could not request data for resource: \(resource), error: \(String(describing: maybeError))")
return
}
let maybeExt = UTTypeCopyPreferredTagWithClass(
resource.uniformTypeIdentifier as CFString,
kUTTagClassFilenameExtension
)?.takeRetainedValue()
guard let ext = maybeExt else {
return
}
guard var fileUrl = inDirectory.appendingPathComponent(NSUUID().uuidString) else {
print("file url error")
return
}
fileUrl = fileUrl.appendingPathExtension(ext as String)
if let buffer = buffer, buffer.write(to: fileUrl, atomically: true) {
print("Saved resource form buffer \(resource) to filepath \(String(describing: fileUrl))")
} else {
PHAssetResourceManager.default().writeData(for: resource, toFile: fileUrl, options: nil) { (error) in
print("Saved resource directly \(resource) to filepath \(String(describing: fileUrl))")
}
}
}
func generateFolderForLivePhotoResources() -> NSURL? {
let photoDir = NSURL(
// NB: Files in NSTemporaryDirectory() are automatically cleaned up by the OS
fileURLWithPath: NSTemporaryDirectory(),
isDirectory: true
).appendingPathComponent(NSUUID().uuidString)
let fileManager = FileManager()
// we need to specify type as ()? as otherwise the compiler generates a warning
let success : ()? = try? fileManager.createDirectory(
at: photoDir!,
withIntermediateDirectories: true,
attributes: nil
)
return success != nil ? photoDir! as NSURL : nil
}
In depth tutorial here Live Photo API on iOS
The question is a little confusing
First, If you want to pick live photo and play live photo.I recommend you use the Photos Framework instead of UIImagePickerController. This way you can fetch the asset and have more control. Then you can play the live photo as mov or the muted version with PHLivePhotoView by setting the startPlayback(with:) to hint or full.
You can refer the code here :
a github repo LivePreview show you how to select live photo and play it.
Second, if you want convert live photo to mov, the code you pasted will work, and if you want to play mov directly, you may want use AVPlayer
Plus, WWDC provides Example app using Photos framework
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let phAsset = info[.phAsset] as? PHAsset
imagePickerController.dismiss(animated: true, completion: nil)
let style = phAsset?.playbackStyle
if(style != .livePhoto) {
print("This is not a live photo")
return
}
let filePath = NSTemporaryDirectory() + String(format: "%.0f", NSDate().timeIntervalSince1970) + "_.mov"
let fileURL = NSURL(fileURLWithPath: filePath)
let options = PHLivePhotoRequestOptions()
options.deliveryMode = .fastFormat
options.isNetworkAccessAllowed = true
PHImageManager.default().requestLivePhoto(for: phAsset!, targetSize: CGSize(width: 1920, height: 1080), contentMode: PHImageContentMode.default, options: options) { livePhoto, info in
if((livePhoto) != nil) {
let assetResources = PHAssetResource.assetResources(for: livePhoto!)
var videoResource : PHAssetResource?
for resources in assetResources {
if(resources.type == .pairedVideo) {
videoResource = resources
break
}
}
guard let videoResource = videoResource else {
fatalError("video resource is nil")
}
PHAssetResourceManager.default().writeData(for: videoResource, toFile: fileURL as URL, options: nil) { error in
let avAsset : AVAsset = AVAsset(url: fileURL as URL)
DispatchQueue.main.async { [self] in
// Whatever you do using fileURL or avAsset.
}
}
}
}
}
Swift 5
func videoUrlForLivePhotoAsset(asset: PHAsset, completionHandler: #escaping (_ result: URL?) -> Void) {
print("videoUrlForLivePhotoAsset: \(asset)")
let options : PHLivePhotoRequestOptions = PHLivePhotoRequestOptions.init()
options.deliveryMode = .fastFormat
options.isNetworkAccessAllowed = true
PHImageManager.default().requestLivePhoto(for: asset, targetSize: UIScreen.main.bounds.size, contentMode: .default, options: options) { (livePhoto, info) in
if livePhoto != nil {
let assetResources : [PHAssetResource] = PHAssetResource.assetResources(for: livePhoto!)
var videoResource : PHAssetResource?
for resource in assetResources {
if resource.type == .pairedVideo {
videoResource = resource
break
}
}
guard let photoDir = self.generateFolderForLivePhotoResources() else {
return
}
print("videoResource: \(videoResource)")
if videoResource != nil {
self.saveAssetResource(resource: videoResource!, inDirectory: photoDir, buffer: nil, maybeError: nil) { (fileUrl) in
completionHandler(fileUrl)
}
}
} else {
completionHandler(nil)
}
}
}
func saveAssetResource(
resource: PHAssetResource,
inDirectory: NSURL,
buffer: NSMutableData?, maybeError: Error?, completionHandler: #escaping (_ result: URL?) -> Void) {
guard maybeError == nil else {
print("Could not request data for resource: \(resource), error: \(String(describing: maybeError))")
return
}
let maybeExt = UTTypeCopyPreferredTagWithClass(
resource.uniformTypeIdentifier as CFString,
kUTTagClassFilenameExtension
)?.takeRetainedValue()
guard let ext = maybeExt else {
return
}
guard var fileUrl = inDirectory.appendingPathComponent(NSUUID().uuidString) else {
print("file url error")
return
}
fileUrl = fileUrl.appendingPathExtension(ext as String)
if let buffer = buffer, buffer.write(to: fileUrl, atomically: true) {
print("Saved resource form buffer \(resource) to filepath \(String(describing: fileUrl))")
completionHandler(fileUrl)
} else {
PHAssetResourceManager.default().writeData(for: resource, toFile: fileUrl, options: nil) { (error) in
print("Saved resource directly \(resource) to filepath \(String(describing: fileUrl))")
if error == nil {
completionHandler(fileUrl)
} else {
completionHandler(nil)
}
}
}
}
func generateFolderForLivePhotoResources() -> NSURL? {
let photoDir = NSURL(
// NB: Files in NSTemporaryDirectory() are automatically cleaned up by the OS
fileURLWithPath: NSTemporaryDirectory(),
isDirectory: true
).appendingPathComponent(NSUUID().uuidString)
let fileManager = FileManager()
// we need to specify type as ()? as otherwise the compiler generates a warning
let success : ()? = try? fileManager.createDirectory(
at: photoDir!,
withIntermediateDirectories: true,
attributes: nil
)
return success != nil ? photoDir! as NSURL : nil
}
Invoke with the following:
let asset = PHAsset.init()
self.videoUrlForLivePhotoAsset(asset: asset!) { (url) in
print("url: \(url)")
}
Note: You need to clean up the Temp and Documents directory, and remove the files.

Get original video name as selected from UIImagePickerController

How can I get the name of video file selected from Camera roll or any other album in UIImagePickerController's delegate method ?
I'm able to get the name of image but if using same in video it's returning nil.
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
if (![mediaType isEqualToString:(NSString *)kUTTypeMovie])
return;
mediaURl = [info objectForKey:UIImagePickerControllerMediaURL];
//NSLog(#"mediaURL %#",mediaURl);
moviePath = mediaURl.absoluteString;
// NSLog(#"moviePath %#",moviePath);
tempFilePath = [[info objectForKey:UIImagePickerControllerMediaURL] path];
NSLog(#"filepath %#",tempFilePath);
//if you want only file name
NSArray *ar = [tempFilePath componentsSeparatedByString:#"/"];
NSString *filename = [[ar lastObject] uppercaseString];
NSLog(#"filename %#",filename);
}
Let me know if you have any issues
I know this thread is super old but i thought if someone finds it, here is a working answer in swift:
func fileName(for infoDict: [String : Any]) -> String? {
guard let referenceURL = infoDict[UIImagePickerControllerReferenceURL] as? URL else { return nil }
let result = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
guard let asset = result.firstObject else { return nil }
let firstResource = PHAssetResource.assetResources(for: asset).first
return firstResource?.originalFilename ?? asset.value(forKey: "filename") as? String
}
Swift 4 or later
Working on My Side for the captured image
Use :
imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
let fileName = FileInfo.getMediaName(info: info)
}
class : pleas put the method info[:]
class FileInfo {
// Return Media name
static func getMediaName(info:[String : Any]) -> String {
if let asset = info[UIImagePickerControllerPHAsset] as? PHAsset {
let assetResources = PHAssetResource.assetResources(for: asset)
let firstObj = assetResources.first?.originalFilename as! NSString
print(firstObj)
return firstObj
}
}
}
// IMG_02256.jpeg

How to convert NSURL to String

I have a CameraVC class start with :
class CameraVC: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagePicker = UIImagePickerController()
var image = UIImage()
var videoFilePath = NSURL()
...
I have this function :
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let mediaType:String = info[UIImagePickerControllerMediaType] as! String
print(mediaType)
if mediaType == "public.image" {
self.image = info[UIImagePickerControllerOriginalImage] as! UIImage
if self.imagePicker.sourceType == UIImagePickerControllerSourceType.Camera {
UIImageWriteToSavedPhotosAlbum(self.image, nil, nil, nil)
}
self.dismissViewControllerAnimated(true, completion: nil)
} else if mediaType == "public.movie" {
self.videoFilePath = info[UIImagePickerControllerMediaURL] as! NSURL
print(self.videoFilePath)
// THIS LINE IS NOT WORK ->
let url = NSURL(string: self.videoFilePath)
/*if self.imagePicker.sourceType == UIImagePickerControllerSourceType.Camera {
if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(self.videoFilePath) {
UISaveVideoAtPathToSavedPhotosAlbum(self.videoFilePath, nil, nil, nil)
}
}*/
}
}
The line :
let url = NSURL(string: self.videoFilePath)
is not working and i have a red alert with "Cannot convert value of type NSURL to expected argument type String.
The line :
print(self.videoFilePath)
write in console log :
file:///private/var/mobile/Containers/Data/Application/071BCA9C-D246-4D14-9D56-34057A17079B/tmp/capture-T0x156501280.tmp.y4Ve7u/capturedvideo.MOV
Try looking at the documentation here: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/#//apple_ref/occ/instp/NSURL/absoluteString
Try let url = NSURL(string: self.videoFilePath.absoluteString)
Also you do realise that self.videoFilePath is already an NSURL...
You have a poorly named variable. self.videoFilePath isn't a path, it's a url. You're making it a URL here:
self.videoFilePath = info[UIImagePickerControllerMediaURL] as! NSURL
If you already have self.videoFilePath as NSURL, you don't have to convert it to String and then NSURL
To keep the code safer:
if let path = info[UIImagePickerControllerMediaURL] as? NSURL {
self.videoFilePath = path
let url = path
//Continue whatever you want
}

Resources