Wednesday, 19 November 2014

Swift + Add UIToolbar or Done Button on Keyboard

   

  override func viewDidLoad()
    {
        super.viewDidLoad()
     
        //--- add UIToolBar on keyboard and Done button on UIToolBar ---//
        self.addDoneButtonOnKeyboard()
        

    }





    //--- *** ---//
    
    func addDoneButtonOnKeyboard()
    {
        var doneToolbar: UIToolbar = UIToolbar(frame: CGRectMake(0, 0, 320, 50))
        doneToolbar.barStyle = UIBarStyle.BlackTranslucent
       
        var flexSpace = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
        var done: UIBarButtonItem = UIBarButtonItem(title: "Done", style: UIBarButtonItemStyle.Done, target: self, action: Selector("doneButtonAction"))
        
        var items = NSMutableArray()
        items.addObject(flexSpace)
        items.addObject(done)
      
        doneToolbar.items = items
        doneToolbar.sizeToFit()
        
        self.textView.inputAccessoryView = doneToolbar
        self.textField.inputAccessoryView = doneToolbar
        
    }
    
    func doneButtonAction()
    {
        self.textViewDescription.resignFirstResponder()
        self.textViewDescription.resignFirstResponder()
    }

Swift + Open UIDatePicker with ActionSheet


// Compatible with iOS 7 and iOS 8 both



var datePicker: UIDatePicker!


override func viewDidLoad()
{
        super.viewDidLoad()
}



     //--- *** ---//

    func createDatePickerViewWithAlertController()
    {
        var viewDatePicker: UIView = UIView(frame: CGRectMake(0, 0, self.view.frame.size.width, 200))
        viewDatePicker.backgroundColor = UIColor.clearColor()
        
        
        self.datePicker = UIDatePicker(frame: CGRectMake(0, 0, self.view.frame.size.width, 200))
        self.datePicker.datePickerMode = UIDatePickerMode.DateAndTime
        self.datePicker.addTarget(self, action: "datePickerSelected", forControlEvents: UIControlEvents.ValueChanged)
        
        viewDatePicker.addSubview(self.datePicker)
        
        
        if(UIDevice.currentDevice().systemVersion >= "8.0")
        {

            let alertController = UIAlertController(title: nil, message: "\n\n\n\n\n\n\n\n\n\n", preferredStyle: UIAlertControllerStyle.ActionSheet)
            
            alertController.view.addSubview(viewDatePicker)
            
            
            
            
            let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel)
                { (action) in
                    // ...
            }
            
            alertController.addAction(cancelAction)
            
            let OKAction = UIAlertAction(title: "Done", style: .Default)
                { (action) in
                    
                    self. dateSelected()
             }
            
            alertController.addAction(OKAction)
            
            /*
            let destroyAction = UIAlertAction(title: "Destroy", style: .Destructive)
            { (action) in
                 println(action)
            }
            alertController.addAction(destroyAction)
            */
            
            self.presentViewController(alertController, animated: true)
            {
                    // ... 
            }

        }
        else
        {
            let actionSheet = UIActionSheet(title: "\n\n\n\n\n\n\n\n\n\n", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: "Done")
            actionSheet.addSubview(viewDatePicker)
            actionSheet.showInView(self.view)
        }

    }


    func dateSelected()
    {
        var selectedDate: String = String()
        
        selectedDate =  Self.dateformatterDateTime(self.datePicker.date)
        
        self.textFieldFromDate.text =  selectedDate

    }


   func dateformatterDateTime(date: NSDate) -> NSString
    {
        var dateFormatter: NSDateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "MM-dd-yyyy h:mm a"
        return dateFormatter.stringFromDate(date)
    }





// Now Implement UIActionSheet Delegate Method just for support for iOS 7 not for iOS 8

    // MARK: - UIActionSheet Delegate Implementation ::
    
    func actionSheet(actionSheet: UIActionSheet!, clickedButtonAtIndex buttonIndex: Int)
    {
        switch buttonIndex
        {
            
        case 0:
            println("Done")
            self. dateSelected()
            break;
        case 1:
            println("Cancel")
            break;
        default:
            println("Default")
            break;
        }
    }


Tuesday, 11 November 2014

Swift + Save and Load Image From DocumentDirectory

var selectedImage: UIImage = "image.png"
            
  
let fileManager = NSFileManager.defaultManager()
            
var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
            
var filePathToWrite = "\(paths)/SaveFile.png"
            
var imageData: NSData = UIImagePNGRepresentation(selectedImage)
            
fileManager.createFileAtPath(filePathToWrite, contents: imageData, attributes: nil)
            
var getImagePath = paths.stringByAppendingPathComponent("SaveFile.png")
            
            
            
if (fileManager.fileExistsAtPath(getImagePath))
{
       println("FILE AVAILABLE");

       //Pick Image and Use accordingly
       var imageis: UIImage = UIImage(contentsOfFile: getImagePath)!
                
       let data: NSData = UIImagePNGRepresentation(imageis)
                
}
else
{
      println("FILE NOT AVAILABLE");

}

Swift + Pick Image From Photo Library Using UIImagePickerController

First Add and Import MobileCoreServices Framework.

Confirm to UIImagePickerControllerDelegate & UINavigationControllerDelegate protocol


import UIKit

import MobileCoreServices


class ViewController: UIViewControllerUIImagePickerControllerDelegateUIAlertViewDelegateUINavigationControllerDelegate
{

    var cameraUI: UIImagePickerController! = UIImagePickerController()
    
    
    override func viewDidLoad()
    {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        
    }

    //--- Take Photo from Photo Library ---//
    @IBAction func takePhotoFromPhotoLibrary(sender: AnyObject)
    {
          self.presentLibrary()
    }



    func presentLibrary()
    {
       
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        {
            cameraUI = UIImagePickerController()
            cameraUI.delegate = self
            cameraUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            cameraUI.mediaTypes = [kUTTypeImage]
            cameraUI.allowsEditing = false
            
            self.presentViewController(cameraUI, animated: true, completion: nil)
        }
        else
        {
            // error msg

        }


    }
    
    //Mark- UIImagePickerController Delegate
    
    func imagePickerControllerDidCancel(picker:UIImagePickerController)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    



    func imagePickerController(picker:UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary)
    {
       if(picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary)
        {
            var selectedImage: UIImage = info[UIImagePickerControllerOriginalImage] as UIImage
            
            //show Image on Image View and do other stuf that you want
            
            self.dismissViewControllerAnimated(true, completion: nil)


        }
       
    }
 


 
}  

Swift + Take pictures and save to camera roll using UIImagePickerController

First Add and Import MobileCoreServices Framework.

Confirm to UIImagePickerControllerDelegate & UINavigationControllerDelegate protocol


import UIKit

import MobileCoreServices


class ViewController: UIViewController, UIImagePickerControllerDelegate, UIAlertViewDelegate, UINavigationControllerDelegate
{

    var cameraUI: UIImagePickerController! = UIImagePickerController()
    
    
    override func viewDidLoad()
    {
        super.viewDidLoad()

    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
        
    }

    //--- Take Photo from Camera ---//
    @IBAction func takePhotoFromCamera(sender: AnyObject)
    {
          self.presentCamera()
    }



    func presentCamera()
    {
       
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
        {
            println("Button capture")
        
            cameraUI = UIImagePickerController()
            cameraUI.delegate = self
            cameraUI.sourceType = UIImagePickerControllerSourceType.Camera;
            cameraUI.mediaTypes = [kUTTypeImage]
            cameraUI.allowsEditing = false
            
            self.presentViewController(cameraUI, animated: true, completion: nil)
        }
        else
        {
            // error msg
        }
    }
    
    //Mark- UIImagePickerController Delegate
    
    func imagePickerControllerDidCancel(picker:UIImagePickerController)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    



    func imagePickerController(picker:UIImagePickerController!, didFinishPickingMediaWithInfo info:NSDictionary)
    {
        if(picker.sourceType == UIImagePickerControllerSourceType.Camera)
        {
            // Access the uncropped image from info dictionary
            var imageToSave: UIImage = info.objectForKey(UIImagePickerControllerOriginalImage) as UIImage
            var imageToSave1: UIImage = info[UIImagePickerControllerOriginalImage] as UIImage //same but with different way
            
            UIImageWriteToSavedPhotosAlbum(imageToSave, nil, nil, nil)
            
            self.savedImageAlert()
            self.dismissViewControllerAnimated(true, completion: nil)

        }
       
    }
    
    
    
    
    func savedImageAlert()
    {
        var alert:UIAlertView = UIAlertView()
        alert.title = "Saved!"
        alert.message = "Your picture was saved to Camera Roll"
        alert.delegate = self
        alert.addButtonWithTitle("Ok")
        alert.show()
    }





}

Swift + Send E-mail In-App using MFMailComposeViewController


In this writing, I want explore how to use MFMailComposeViewController with Swift to send e-mails within your app as a walkthrough.


First Add and Import MessageUI Framework.



import UIKit
import MessageUI



Second, we need to specify that the View Controller will conform to
the MFMailComposeViewControllerDelegate protocol.  Later, we’ll actually implement the method that this protocol outlines, which will allow us to make the email composer screen go away once the user is finished either sending an e-mail or cancels out of sending one.




@IBAction func sendEmailButtonTapped(sender: AnyObject)
{
        let mailComposeViewController = configuredMailComposeViewController()
       
        if MFMailComposeViewController.canSendMail()
        {
            self.presentViewController(mailComposeViewController, animated: true, completion: nil)
        }
        else
        {
            self.showSendMailErrorAlert()
        }
}








   func configuredMailComposeViewController() -> MFMailComposeViewController
    {
        let mailComposerVC = MFMailComposeViewController()
    
        mailComposerVC.mailComposeDelegate = self
        
        
        mailComposerVC.setToRecipients(["test@domain.com"])
        
        
        mailComposerVC.setSubject("Sending you an in-app e-mail...")
        
        
        mailComposerVC.setMessageBody("Sending e-mail in-app is not so bad!", isHTML: false)
        
        return mailComposerVC
        
    }
    
    
    
    
    
    func showSendMailErrorAlert()
    {
        
        
        let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail.  Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
        
        
        sendMailErrorAlert.show()
        
        
    }
    
    
    
    
    
    // MARK: MFMailComposeViewControllerDelegate Method
    
    
    func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!)
    {
        
        
        controller.dismissViewControllerAnimated(true, completion: nil)
        
        
    }

Swift + CLGeocoder to show address string on Map

First of all add & Import MapKit framework in your class.

import UIKit
import MapKit

class ViewController: UIViewControllerCLLocationManagerDelegate
{

    @IBOutlet weak var map: MKMapView!
    
  
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
       self.map.mapType = MKMapType.Standard
       self.map.showsUserLocation = true
        
       self.map.removeAnnotations(self.map.annotations)

     

         let address = "address string"
        
        var geocoder:CLGeocoder = CLGeocoder()
        
        geocoder.geocodeAddressString(address, completionHandler: {(placemarks: [AnyObject]!, error: NSError!) -> Void in
            
            if(error != nil)
            {
                
                println("Error", error)
            }
                
            else if let placemark = placemarks?[0] as? CLPlacemark
            {
                
                var placemark:CLPlacemark = placemarks[0] as CLPlacemark
                var coordinates:CLLocationCoordinate2D = placemark.location.coordinate
                
                var pointAnnotation:MKPointAnnotation = MKPointAnnotation()
                pointAnnotation.coordinate = coordinates
                pointAnnotation.title = "Apple HQ"
                
                self.map.addAnnotation(pointAnnotation)
                self.map.centerCoordinate = coordinates
                self.map.selectAnnotation(pointAnnotation, animated: true)
                
                println("Added annotation to map view")
            }
            
        })

    }

    override func didReceiveMemoryWarning()
    {
        super.didReceiveMemoryWarning()
       
    }

}