Thursday, September 29, 2016

UIimagePickerController Example using Swift 3

UIimagePickerController using we grab photo from photo library or take a picture using camera.

At first we need to add some protocol for UIImagePickerController like UIImagePickerControllerDelegate and UINavigationControllerDelegate on our ViewController.

Looks like
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
}

Image Picker Setup for photo library and camera

    //MARK: Action
    @IBAction func imagePickFromPhotoLib(_ sender: UIButton) {
        let imagePickerController = UIImagePickerController()
        // imagePickerController.allowsEditing = true
        imagePickerController.delegate = self
        imagePickerController.sourceType = .photoLibrary
        present(imagePickerController, animated: true, completion: nil)
    }

    @IBAction func imagePickFromCamera(_ sender: UIButton) {
        let imagePickerController = UIImagePickerController()
        imagePickerController.sourceType = .camera
        imagePickerController.allowsEditing = true
        imagePickerController.cameraDevice = .front
        imagePickerController.cameraFlashMode = .auto
        imagePickerController.delegate = self
        present(imagePickerController, animated: true, completion: nil)
    }

Then we need to implement delegate

   //MARK: UIImagePickerDelegate
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }

      func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo  info: [String : Any]) {
       
        let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        // picker selected image use on what ever we need
        picker.dismiss(animated: true, completion: nil)
    }

Info.plist file add those key 

Privacy - Camera Usage Description
Privacy - Photo Library Usage Description


Here demo project on git.

Tuesday, September 27, 2016

Email validation in swift


    func validateEmail(emailAddress:String)->Bool{

        let emailRegularExpression = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
       
        let emailValidationPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegularExpression)
       
        return emailValidationPredicate.evaluate(with: emailAddress)
       
    }

Introduction to UIAlertController, Swift 3.0.

    let learningAlertController = UIAlertController(title: "Hello!!!", message: "I'm alert controller", preferredStyle: .alert)

    let okAlertAction = UIAlertAction(title: "OK", style: .default) { (action:UIAlertAction) in
        print("You've pressed OK button");
    }
    learningAlertController.addAction(okAlertAction)
    present(learningAlertController, animated: true, completion: nil)