Select video from PhotoLibrary in iOS using Swift - ios

I am trying to select video from PhotoLibrary using following code
imageController.mediaTypes = [kUTTypeMovie: NSString]
After selecting video, when it is compressing, I am getting array out of boundary issue.
I searched online and found following line. I am unable to convert it into Swift version (link)
imageController.mediaTypes = [[NSArray alloc] initWithObjects:(NSString *)kUTTypeMovie, nil]
Please let us know the Swift version for above line. It is very useful if anyone can provide Swift version of this.
Question2:
I want to show selected video in app and need to play when it is tapped. Can we do it without external plugins and using built in libraries?

Based on Swift 2.2
Suppose you have a imagePickerController and when you want to select both images and videos:
let imagePickerController = UIImagePickerController()
var videoURL: NSURL?
#IBAction func selectImageFromPhotoLibrary(sender: UIBarButtonItem) {
imagePickerController.sourceType = .PhotoLibrary
imagePickerController.delegate = self
imagePickerController.mediaTypes = ["public.image", "public.movie"]
presentViewController(imagePickerController, animated: true, completion: nil)
}
Then after the video is selected, print out its NSURL.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
videoURL = info["UIImagePickerControllerReferenceURL"] as? NSURL
print(videoURL)
imagePickerController.dismissViewControllerAnimated(true, completion: nil)
}
For question 2:
Yes, you can do it through AVPlayer, you need import AVKit and AVFoundation, and you code may look like this:
if let videoURL = videoURL{
let player = AVPlayer(URL: videoURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
I made a demo here you can refer, maybe not 100% what you want.

#IBOutlet weak var imgView: UIImageView!
var imagePickerController = UIImagePickerController()
var videoURL : NSURL?
#IBAction func btnSelectVideo_Action(_ sender: Any) {
imagePickerController.sourceType = .savedPhotosAlbum
imagePickerController.delegate = self
imagePickerController.mediaTypes = [kUTTypeMovie as String]
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
videoURL = info[UIImagePickerControllerMediaURL]as? NSURL
print(videoURL!)
do {
let asset = AVURLAsset(url: videoURL as! URL , options: nil)
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(0, 1), actualTime: nil)
let thumbnail = UIImage(cgImage: cgImage)
imgView.image = thumbnail
} catch let error {
print("*** Error generating thumbnail: \(error.localizedDescription)")
}
self.dismiss(animated: true, completion: nil)
}
For question 2:
let player = AVPlayer(url: videoURL)
let playerController = AVPlayerViewController()
playerController.player = player
self.present(playerController, animated: true) {
player.play()
}

Swift 5+ solution:
func openVideoGallery() {
picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .savedPhotosAlbum
picker.mediaTypes = ["public.movie"]
picker.allowsEditing = false
present(picker, animated: true, completion: nil)
}

Swift 3
import MobileCoreServices
var imagePickerController = UIImagePickerController()
var videoURL: URL?
private func openImgPicker() {
imagePickerController.sourceType = .savedPhotosAlbum
imagePickerController.delegate = self
imagePickerController.mediaTypes = ["public.movie"]
present(imagePickerController, animated: true, completion: nil)
}
extension YourViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
videoURL = info[UIImagePickerControllerMediaURL] as? URL
print("videoURL:\(String(describing: videoURL))")
self.dismiss(animated: true, completion: nil)
}
}

func openCamera() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
println("captureVideoPressed and camera available.")
var imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
imagePicker.mediaTypes = [kUTTypeMovie!]
imagePicker.allowsEditing = false
imagePicker.showsCameraControls = true
self.presentViewController(imagePicker, animated: true, completion: nil)
} else {
println("Camera not available.")
}
}
func imagePickerController( didFinishPickingMediaWithInfo info:NSDictionary!) {
videoUrl = info[UIImagePickerControllerMediaURL] as! NSURL!
let pathString = videoUrl.relativePath
self.dismissViewControllerAnimated(true, completion: nil)
}

Swift 4.0
Your class adopts the UIImagePickerControllerDelegate protocol
class classname: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate
After that you need to create
let imagePickerController = UIImagePickerController()
Add this in your button's action:-
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
imagePickerController.mediaTypes = ["public.image", "public.movie"]
present(imagePickerController, animated: true, completion: nil)
Delegate method
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let videoURL = info["UIImagePickerControllerReferenceURL"] as? NSURL
print(videoURL!)
imagePickerController.dismiss(animated: true, completion: nil)
}

Select a Video from Gallery using Swift 4
// Put this code where you want to pick the video from gallery
Let imagePickerController = UIImagePickerController ()
imagePickerController.sourceType = .photoLibrary
imagePickerController.delegate = self
imagePickerController.mediaTypes = ["public.movie"]
present(imagePickerController, animated: true, completion: nil)
// UIImagePickerController Delegate Method
func imagePickerController (_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: Any])
{
let videoURL = info[UIImagePickerControllerMediaURL] as? NSURL
print(videoURL!)
self.dismiss(animated: true, completion: nil)
}

try this pod that i've made :
https://github.com/jhonyourangel/ImagePickerWhatsApp
I was searching for a similar Image and Video Picker for a project and i wasn't able to find one that was able to :
1. Take picture
2. Get a Picture from the library
3. Register a Video
4. Get a video from the library
While i was looking i hopen whatsup of facebook or mabe google have a pod for this kind of needs, i realy liked the whatsapp picker, so i created this one similer to the one in whatsapp.
Prerequisites
In order to use ImageVideoPicker you need cocoapods and an xCode project already created
Installing
to install cocoapods is should be enough just to run sudo gem install cocoapods in the terminal
if this doen't work go to cocoapods
Then navigate the terminal to your project folder, where the file extension .xcodeproj is located and run pod init
this will create a file called Podfile
Open the file in a editor ( sublimeText, xCode, atom, vim ... etc ) and add the line bellow after use_frameworks!
pod 'ImagePickerWhatsApp'
or
pod 'ImagePickerWhatsApp', :path => '/Users/aiu/Documents/cocoapods/ImagePickerWhatsApp'
then just run pod install in the terminal and wait to finish instaling the lib
How to use it
add import ImagePickerWhatsApp to your viewcontroller class
then you can call the picker by calling :
let mp = ImageVideoPicker.makeVCFromStoryboard()
self.present(mp, animated: true, completion: nil)
Delegate
to implement the delegate add mp.delegate = self and the extent the class of you view controller
aso you need to import the iOS Photos framework import Photos
extension ViewController: ImageVideoPickerDelegate {
func onCancel() {
print("no picture selected")
}
func onDoneSelection(assets: [PHAsset]) {
print("selected \(assets.count) assets")
}
}
the func onDoneSelection returns an array of assets that contain the info of where the asset is located : on the device, iTunes library or iCloud.
if you just need to display the images you can use the this code in a collection view or something similar just implement this peace of code
var representedAssetIdentifier: String!
func getImageFrom(asset: Phasset) {
representedAssetIdentifier = asset?.localIdentifier
let imageManager = PHCachingImageManager()
imageManager.requestImage(for: asset!, targetSize: self.frame.size, contentMode: .default, options: nil) { (image, _) in
if(self.representedAssetIdentifier == self.asset?.localIdentifier &&
image != nil) {
self.imageView.image = image
}
}
}
this will show just the thumbnail, but is awesome because is also showing the thumbnail for live photos, and videos
Images and Videos as Data
The lib is intended to be used for sending images or videos over the network, and not to do fancy image or video editing. But this doesn't mea you can't. You can do just about anything since it returns an array of assets, but is you job to implement what you need.
in order to get the data from the asset ImageVideoPicker has one method that will return an completition handler with the data.
ImageVideoPicker.getDataFrom(asset: asset) { (data) in
if data == nil {
print(data as Any, asset.mediaType, asset.localIdentifier)
} else {
print(data!.count as Any, asset.mediaType, asset.localIdentifier)
}
}
that will be all
have fun

func startMediaBrowserFromViewController(viewController: UIViewController!, usingDelegate delegate : protocol<UINavigationControllerDelegate, UIImagePickerControllerDelegate>!) -> Bool {
if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) == false {
return false
}
let mediaUI = UIImagePickerController()
mediaUI.sourceType = .SavedPhotosAlbum
mediaUI.mediaTypes = [kUTTypeMovie as String]
mediaUI.allowsEditing = true
mediaUI.delegate = delegate
presentViewController(mediaUI, animated: true, completion: nil)
return true
}

Updated for the current version of Swift:
// Check if the asset is of video media type.
guard (asset.mediaType == PHAssetMediaType.video) else {
print("Not a valid video media type")
return
}
// Obtain the URL of the video.
PHCachingImageManager().requestAVAsset(forVideo: asset, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [AnyHashable : Any]?) in
let asset = asset as! AVURLAsset
print("asset.url: ", asset.url) // Here is video URL
// Play the video.
DispatchQueue.main.async(execute: {
let player = AVPlayer(url: asset.url)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
})
})

if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
println("Camera Available")
var imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
Delegate method
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
self.dismissViewControllerAnimated(true, completion: nil)
imageView.image = image
}

Related

iOS Swift - Video picker from library/gallery

I'm trying to implement a feature to pick videos from the gallery from an iPhone.
Here is my function :
func openVideoGallery()
{
let picker = UIImagePickerController()
picker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
picker.sourceType = .savedPhotosAlbum
picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .savedPhotosAlbum)!
picker.mediaTypes = ["public.movie"]
picker.allowsEditing = false
present(picker, animated: true, completion: nil)
}
Here is my questions :
I was wondering is it the right way to pick up videos from the gallery using UIImagePickerController ?
How can I get the path to video selected ?
Thank you for your help ^^
1- Yes
2- implemet
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let asset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
asset.getURL { (tempPath) in
}
}
else if let media = info[UIImagePickerController.InfoKey.mediaURL] as? URL {
}
else
if let ref = info[UIImagePickerController.InfoKey.referenceURL] as? URL {
}
}
Change this
picker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
to
picker.delegate = self
and make the vc conform to
class VCName: UIViewController,UIImagePickerControllerDelegate & UINavigationControllerDelegate {

iOS camera freezes when previewing video when there is a camera overlay

I am attempting to overlay a view over a video capture session in UIImagePicker. The overlay works fine but when the app gets to the screen where the user can "retake", "play" or "use video", the app crashes and gives the error:
2017-04-16 21:33:04.129212-0400 ChugMug[429:59833] libMobileGestalt
MobileGestalt.c:2690: statfs(/mnt4): No such file or directory
2017-04-16 21:33:04.129871-0400 ChugMug[429:59833] libMobileGestalt
MobileGestalt.c:2587: SInt64 NANDSize(): No kIOMediaSizeKey found for
disk0! 2017-04-16 21:33:09.352085-0400 ChugMug[429:60065]
[MediaRemote] Error Operation requires a client callback to have been
registered. requesting playback queue
The code is quite simple, when the overlay is commented out, the video preview screen and buttons work fine, but when the overlay is present the app freezes at the following screen:
Here is the code for the camera and the overlay:
func startMediaBrowserFromViewController(viewController: UIViewController, usingDelegate delegate: UINavigationControllerDelegate & UIImagePickerControllerDelegate) -> Bool {
// 1
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) == false {
return false
}
// 2
let mediaUI = UIImagePickerController()
mediaUI.sourceType = .savedPhotosAlbum
mediaUI.mediaTypes = [kUTTypeMovie as NSString as String]
mediaUI.allowsEditing = true
mediaUI.delegate = delegate
// 3
present(mediaUI, animated: true, completion: nil)
return true
}
func startCameraFromViewController(viewController: UIViewController, withDelegate delegate: UIImagePickerControllerDelegate & UINavigationControllerDelegate) -> Bool {
if UIImagePickerController.isSourceTypeAvailable(.camera) == false {
return false
}
cameraController.sourceType = .camera
cameraController.mediaTypes = [kUTTypeMovie as NSString as String]
cameraController.allowsEditing = false
cameraController.delegate = delegate
cameraController.showsCameraControls = true
//customView stuff
let customViewController = CustomOverlayViewController(
nibName:"CustomOverlayViewController",
bundle: nil
)
let customView = customViewController.view //as! CustomOverlayView
customView?.frame = cameraController.view.frame
present(cameraController, animated: true, completion: {
self.cameraController.cameraOverlayView = customView
customViewController.cameraLabel.text = "Camera Label"
self.cameraController.startVideoCapture()
})
return true
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
dismiss(animated: true, completion: nil)
// Handle a movie capture
if mediaType == kUTTypeMovie {
guard let path = (info[UIImagePickerControllerMediaURL] as! NSURL).path else { return }
if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(path) {
UISaveVideoAtPathToSavedPhotosAlbum(path, self, nil, nil)
}
}
}
I have no clue what is causing this strange error and cant find anything similar. I hope someone can help me.

Swift 3 - How do I use a photolibrary picture in an app?

How can I use a picture from the Photo Library in my app? I have done the tutorials about credating a photo app. That all works fine. I have a UIPickerController, can take a picture with the camera, save it to the library, or select an image from the library, which is then put onto the screen. But...
What I want is that the user selects a picture, remember the name of the picture or the number or something, and then on another page use this picture from the library.
Like selecting an avatar. Saving the picture somewhere and whenever the user enters the profile page, open up this avatar picture previously selected. So what I need is the "name"(represenation) of the picture, but I can't find that. How do I do that?
(the code below is just the working cam/lib app part, but it saves the picture without name, that's the problem: How do I find out what picture was saved earlier?) P.S. Sorry, variable names are in Dutch.
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var plaatje: UIImageView!
#IBAction func saveknop(_ sender: UIButton) {
let imageData = UIImageJPEGRepresentation(plaatje.image!, 0.6)
let compressedfoto = UIImage(data: imageData!)
UIImageWriteToSavedPhotosAlbum(compressedfoto!, nil, nil, nil)
saveNotice()
}
#IBAction func cameraknop(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
#IBAction func biepknop(_ sender: Any) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.allowsEditing = true
self.present(imagePicker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
plaatje.image = image
self.dismiss(animated: true, completion: nil)
}
func saveNotice() {
let alert = UIAlertController(title: "foto genomen", message: "je foto is bewaard in de biep", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(defaultAction)
present(alert, animated: true, completion: nil)
}
}
One solution I found is to use UIImageJPEGRepresentation or UIImagePNGRepresentation to convert the image into a Data object. From there you can use the write(to:) method to save it to the specific URL you want your app to use.
The answer to this SO question shows a few ways to store the image. It might be of help.
I had the same trouble earlier, this did the trick for me:
Save images using the following method:
func saveImage(image: UIImage, path: String ) {
let pngImageData = UIImagePNGRepresentation(image)
do {
try pngImageData?.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch {
print(error)
}
}
Load saved images using:
func loadImageFromName(name: String) -> UIImage? {
let path = self.fileInDocumentsDirectory(filename: name)
let image = UIImage(contentsOfFile: path)
if image == nil {
print("Image not available at: \(path)")
}
return image
}
func fileInDocumentsDirectory(filename: String) -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
return documentsFolderPath.appendingPathComponent(filename)
}
Call the save method like this:
saveImage(image: image, path: fileInDocumentsDirectory(filename: "someId"))
Good luck! Hope this helps.
Struggeling with the suggestions, I found another solution, that is strangely simple. But it works! Weird. It is not the best one, but for now I'll use this, untill I understand everyuthiong about the directorys and filesystem on the iphone.
P.S. credit goes to: http://theswiftguy.com/index.php/2016/11/10/how-to-save-an-image-locally-in-xcode-8-swift-3-0/
//Encoding
let image = UIImage(named: "dog.png")
let imageData:NSData = UIImagePNGRepresentation(image!)! as NSData
//Saved image
UserDefaults.standard.set(imageData, forKey: "savedImage")
//Decode
let data = UserDefaults.standard.object(forKey: "savedImage") as! NSData
myImageView.image = UIImage(data: data as Data)

Why doesn't UIImagePickerController delegate to my Object class?

class CameraPicker: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
weak var viewController:MyProfileVC!
func launchCamera() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
let imagePicker:UIImagePickerController = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.front
imagePicker.cameraCaptureMode = .photo
imagePicker.allowsEditing = false
self.viewController.present(imagePicker, animated: true, completion: nil)
} }
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
print("didFinishPickingMedia")
}
This is my object class function, but 'didFinishPickingMediaWithInfo' function doesn't get called after taking the picture. Also, the viewcontroller which is presenting the imagepicker is a different Swift file
I had the same problem and I've found a solution, so I'm posting my version (I'm taking a picture from the photo library but it's the same :) ).
I had a memory management issue.
I've created an IBAction function where I instantiated my camera handler class (with the delegate inside...). At the end of the function the variable goes out of scope and it's deallocated. To solve the issue I've made it as instance variable.
That's my code for the VC with my UiButton:
class STECreateUserVC: UIViewController {
#IBOutlet weak var imgAvatar: UIImageView!
let cameraHandler = STECameraHandler()
#IBAction func buttonPressed(_ sender: UIButton) {
cameraHandler.importPictureIn(self) { [weak self] (image) in
self?.imgAvatar.image = image
}
}
}
...and that's my handler:
class STECameraHandler: NSObject {
let imagePickerController = UIImagePickerController()
var completitionClosure: ((UIImage) -> Void)?
func importPictureIn(_ viewController: UIViewController, completitionHandler:((UIImage) -> Void)?) {
completitionClosure = completitionHandler
imagePickerController.delegate = self
imagePickerController.allowsEditing = true
imagePickerController.sourceType = .photoLibrary
imagePickerController.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
viewController.present(imagePickerController, animated: true, completion: nil)
}
}
extension STECameraHandler: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let completitionClosure = completitionClosure, let image = info[UIImagePickerControllerEditedImage] as? UIImage {
completitionClosure(image)
}
imagePickerController.dismiss(animated: true)
}
}
I've used a closure in order to have a cleaner code.
This:
self.viewController.present(imagePicker, animated: true, completion: nil)
should be:
self.present(imagePicker, animated: true, completion: nil)

Add a circular cropping component for UIImagePicker?

I Have a circular framed UIImageView and I need to add a circular framed cropping tool for the UIImagePickerController, after the image is selected from a photo library. Very similar to Instagram's UIImagePicker's crop component. How do I add this type of component?
UPDATE
I've found this repo with a circular cropping tool https://github.com/ruslanskorb/RSKImageCropper
but can someone guide me on to how to implement this cropping tool with the UIImagePickerController after the user selects a photo from the photo library?
UPDATE
I am getting the following message in my debugger :
and the buttons in my crop view are disabled, meaning I cannot select them.. what message is the debugger relaying on to me?
here is my code:
#IBAction func chooseProfilePicture(sender: AnyObject) {
var myPickerController = UIImagePickerController()
myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
var image : UIImage = (info[UIImagePickerControllerOriginalImage] as? UIImage)!
editProfilePictureImageView.image = image
self.dismissViewControllerAnimated(false, completion: { () -> Void in
var imageCropVC : RSKImageCropViewController!
imageCropVC = RSKImageCropViewController(image: image, cropMode: RSKImageCropMode.Circle)
imageCropVC.delegate = self
self.navigationController?.pushViewController(imageCropVC, animated: true)
})
}
Example Demo
Yes you can add RSKImageCropper in your UIImagePickerController
define imagePicker
var imagePicker : UIImagePickerController!
in ViewDidLoad
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
self.presentViewController(imagePicker, animated: true, completion: nil)
Delegate methode :
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
var image : UIImage = (info[UIImagePickerControllerOriginalImage] as? UIImage)!
picker.dismissViewControllerAnimated(false, completion: { () -> Void in
var imageCropVC : RSKImageCropViewController!
imageCropVC = RSKImageCropViewController(image: image, cropMode: RSKImageCropMode.Circle)
imageCropVC.delegate =self
self.navigationController?.pushViewController(imageCropVC, animated: true)
})
}
see :
Kirit Modi's answer was exactly what I needed, although I needed to do one thing to make this work. For those that dont download the test project, make sure to implement your delegate methods:
Swift 3:
extension YourViewControllerClass: RSKImageCropViewControllerDelegate {
func imageCropViewControllerDidCancelCrop(_ controller: RSKImageCropViewController) {
_ = self.navigationController?.popViewController(animated: true)
}
func imageCropViewController(_ controller: RSKImageCropViewController, didCropImage croppedImage: UIImage, usingCropRect cropRect: CGRect) {
self.avatarImageView.image = croppedImage
_ = self.navigationController?.popViewController(animated: true)
}
}
Swift 2:
extension YourViewControllerClass: RSKImageCropViewControllerDelegate {
func imageCropViewControllerDidCancelCrop(controller: RSKImageCropViewController) {
self.navigationController?.popViewControllerAnimated(true)
}
func imageCropViewController(controller: RSKImageCropViewController, didCropImage croppedImage: UIImage, usingCropRect cropRect: CGRect) {
self.avatarImageView.image = croppedImage
self.navigationController?.popViewControllerAnimated(true)
}
}
For Swift 2.2:
add delegate methods to your class:
class ViewController: UIViewController, UIImagePickerControllerDelegate, RSKImageCropViewControllerDelegate, UINavigationControllerDelegate
define imagePicker
var imagePicker : UIImagePickerController!
in viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(imagePicker, animated: true, completion: nil)
And delegate methode :
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
let image : UIImage = image
picker.dismissViewControllerAnimated(false, completion: { () -> Void in
var imageCropVC : RSKImageCropViewController!
imageCropVC = RSKImageCropViewController(image: image, cropMode: RSKImageCropMode.Circle)
imageCropVC.delegate = self
self.navigationController?.pushViewController(imageCropVC, animated: true)
})
}
Of course it need to do bridge for objective C class
Oh, link to RSKImageCrop

Resources