How to convert NSURL to String - ios

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
}

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]

How to wait the upload function return true(the object in server exist.) to do next? Swift

I have an upload image function in "didFinishPickingMediaWithInfo".
when I pick photo done, start uploading image.
But when I in editing View, I click the "choose" button, the view doesn't dismiss that look like locked, press anything doesn't work.
I guess my check sever function whether have the image or not, make it locked.Sorry I'm beginner and already search the stack overflow,I dont know what answer can solve this problem.
let albumPicker = UIImagePickerController()
albumPicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
albumPicker.delegate = self
albumPicker.allowsEditing = true
self.present(albumPicker, animated: true, completion: nil)
internal func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let uuid = NSUUID().uuidString
let imageName:String = uuid + ".jpg"
let documentsPath = NSHomeDirectory().appending("/Documents/")
let imagePath = documentsPath.appending(imageName)
let imageUrl = URL(fileURLWithPath: imagePath)
photoImage = info[UIImagePickerControllerOriginalImage] as? UIImage
if picker.sourceType == .camera {
photoImage = info[UIImagePickerControllerOriginalImage] as? UIImage
UIImageWriteToSavedPhotosAlbum(photoImage!, nil, nil, nil)
}
showLoadingView()
hideLoadingView {
//uploading
let objectKey:String = imageName
oss.uploadObjectAsync(imageUrl, objectKey: objectKey)
oss.checkObjectExist(objectKey: objectKey)
//this is check server object
//First,I want to check the object exist ,and send message
let message = "http:104.168.1.111/\(imageName)"
self.sendMessage(message: message)
self.tableView.scrollToBottom()
self.dismiss(animated: true, completion: nil) //sometimes donesnt work.
}
}
var client:OSSClient?
func checkObjectExist(objectKey:String) {
let put:OSSPutObjectRequest = OSSPutObjectRequest()
put.bucketName = ossBucketName
put.objectKey = objectKey
do {
try client?.doesObjectExist(inBucket: put.bucketName, objectKey: put.objectKey)
} catch {
//debug(object: error)
print("*****ERROR HERE: \(error)")
}
}
"doesObjectExist" document says
open func doesObjectExist(inBucket bucketName: String, objectKey: String) throws
return YES Object exist
return NO && *error = nil Object don't exist
return NO && *error != nil error
Thanks.

Error: Cannot assign a value of type 'AnyObject?' to a value of type 'NSURL'

Geting error : Cannot assign a value of type 'AnyObject?' to a value of type 'NSURL'
My code:
var videoPlayer = MPMoviePlayerController()
var mediaUI = UIImagePickerController()
var videoURL = NSURL()
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
// error in below first line
self.videoURL = info[UIImagePickerControllerMediaURL]
mediaUI.dismissViewControllerAnimated(true, completion: nil)
self.videoPlayer = MPMoviePlayerController()
self.videoPlayer.contentURL = videoURL
self.videoPlayer.view.frame = CGRectMake(0,0,self.view.frame.size.width,460)
self.view.addSubview(self.videoPlayer.view)
self.videoPlayer.play()
}
How to change that code to resolve my error.
info[UIImagePickerControllerMediaURL] is of type AnyObject? but self.videoURL is of type NSURL.
Safely cast the result as NSURL:
if let vURL = info[UIImagePickerControllerMediaURL] as? NSURL {
self.videoURL = vURL
}
Here's your code fixed:
var videoPlayer = MPMoviePlayerController()
var mediaUI = UIImagePickerController()
var videoURL = NSURL()
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let vURL = info[UIImagePickerControllerMediaURL] as? NSURL {
self.videoURL = vURL
} else {
print("oops, no url")
}
mediaUI.dismissViewControllerAnimated(true, completion: nil)
self.videoPlayer = MPMoviePlayerController()
self.videoPlayer.contentURL = videoURL
self.videoPlayer.view.frame = CGRectMake(0,0,self.view.frame.size.width,460)
self.view.addSubview(self.videoPlayer.view)
self.videoPlayer.play()
}

Get Image from Selected Video UIImagePickerController

How can i retrieve or make a thumbnail image of the selected video to be used in a another view controller after the video has been selected by user?
func imagePickerController1(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
// 1
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
// 2
dismissViewControllerAnimated(true) {
// 3
if mediaType == kUTTypeMovie {
let moviePlayer = MPMoviePlayerViewController(contentURL: info[UIImagePickerControllerMediaURL] as! NSURL)
self.presentMoviePlayerViewControllerAnimated(moviePlayer)
}
}
let destination = self.storyboard!.instantiateViewControllerWithIdentifier("FinializePost")
self.navigationController!.pushViewController(destination, animated: true);
}
You can use this code:
let URL_originalvideo = info[UIImagePickerControllerMediaURL]
let asset: AVAsset = AVAsset.assetWithURL(URL_originalvideo) as AVAsset
let imageGenerator = AVAssetImageGenerator(asset: asset);
let time = CMTimeMakeWithSeconds(1.0, 1)
var actualTime : CMTime = CMTimeMake(0, 0)
var error : NSError?
let myImage = imageGenerator.copyCGImageAtTime(time, actualTime: &actualTime, error: &error)
myImage is what you need.

Save video on the gallery and store the path to the video

I have an app in which the user can record a video, this video is saved in the photo gallery, and I store the path to the video so that in the future the user could see again the video inside the app. The problem is that the method that I use I think it's giving me some kind of temporary path, and after some days, the video still in the gallery, but the path is not valid anymore and make the app crash. This is the code I'm using:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let mediaType: String = info["UIImagePickerControllerMediaType"] as! String
if mediaType == "public.movie" {
let tempImageURL = info[UIImagePickerControllerMediaURL] as! NSURL!
let pathString = tempImageURL.relativeString
self.dismissViewControllerAnimated(true, completion: {})
if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary {
self.videoPath = pathString
// Save the path in the DB
} else {
VideoManager.saveVideo(tempImageURL, onComplete: { (path) -> Void in
self.videoPath = path
// Save the path in the DB
})
var fileManager: NSFileManager = NSFileManager()
fileManager.removeItemAtPath(pathString!, error: nil)
}
}
}
And the VideoManager.saveVideo method code is the following:
func saveVideo(videoURL: NSURL, onComplete:((path: String) -> Void)) {
var assetsLibrary: ALAssetsLibrary = ALAssetsLibrary()
assetsLibrary.writeVideoAtPathToSavedPhotosAlbum(videoURL, completionBlock: { (assetURL: NSURL!, error: NSError!) -> Void in
var path: String = error == nil ? "\(assetURL)" : kEmptyString
onComplete(path: path)
})
}
I don't know what I'm doing wrong, I've tried with the method UISaveVideoAtPathToSavedPhotosAlbum but without success.. Any ideas?
For giving a little more information, when the video is selected from the gallery, the url I get is like the following one:
file:///private/var/mobile/Containers/Data/Application/D2E8E31B-CEA0-43B0-8EF9-1820F6BDE4A9/tmp/trim.AD855155-AB78-4A16-9AA8-DF2B3F39824E.MOV
And when I record a new video using the camera, first I have this URL:
file:///private/var/mobile/Containers/Data/Application/D2E8E31B-CEA0-43B0-8EF9-1820F6BDE4A9/tmp/capture/capturedvideo.MOV
and when I do writeVideoAtPathToSavedPhotosAlbum it returns an URL like:
assets-library://asset/asset.MOV?id=958507B5-1353-4DDC-BC07-D9CBC6126657&ext=MOV
Both of them work, but some days later stop working.
OK finally I found the solution, the thing was that you can't access directly the photo gallery with the stored url, you got to use the assetLibrary.assetForURL method, which I was missing. In the end the imagepickercontroller delegate method is like this:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
let mediaType: String = info["UIImagePickerControllerMediaType"] as! String
if mediaType == "public.movie" {
self.dismissViewControllerAnimated(true, completion: {})
if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary {
let tempImageURL = info[UIImagePickerControllerReferenceURL] as! NSURL!
self.videoPath = tempImageURL.absoluteString
} else {
let tempImageURL = info[UIImagePickerControllerMediaURL] as! NSURL!
VideoManager.saveVideo(tempImageURL, onComplete: { (path) -> Void in
self.videoPath = path
})
}
}
}
I also was missing that when you record a video, you got to obtain the url using:
let tempImageURL = info[UIImagePickerControllerMediaURL] as! NSURL!
But when you get the video you have to do:
let tempImageURL = info[UIImagePickerControllerReferenceURL] as! NSURL!
Hope it helps!!

Resources