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()
       
    }

}

Monday 10 November 2014

Swift + CLGeocoder to get address from current location

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

If you are working with iOS 8 you must include the NSLocationAlwaysUsageDescription key in info.plist file of your current project to get the location services to work.


import UIKit
import CoreLocation

class ViewController: UIViewControllerCLLocationManagerDelegate
{

    let locationManager = CLLocationManager()
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
      }

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

  

        //--- Find Address of Current Location ---//
    @IBAction func findMyLocation(sender: AnyObject)
    {
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        
        
       let location = self.locationManager.location
        
        var latitude: Double = location.coordinate.latitude
        var longitude: Double = location.coordinate.longitude
        
        println("current latitude :: \(latitude)")
        println("current longitude :: \(longitude)")
        

    }






   You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
    {
                 //--- CLGeocode to get address of current location ---//
        CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: {(placemarks, error)->Void in
            
            if (error != nil)
            {
                println("Reverse geocoder failed with error" + error.localizedDescription)
                return
            }
            
            if placemarks.count > 0
            {
                let pm = placemarks[0] as CLPlacemark
                self.displayLocationInfo(pm)
            }
            else
            {
                println("Problem with the data received from geocoder")
            }
        })        

    }


    func displayLocationInfo(placemark: CLPlacemark?)
    {
        if let containsPlacemark = placemark
        {
            //stop updating location to save battery life
            locationManager.stopUpdatingLocation()
            
            let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
            let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
            let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
            let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
            
            println(locality)
            println(postalCode)
            println(administrativeArea)
            println(country)
        }
        
    }
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
    {
        println("Error while updating location " + error.localizedDescription)
    }




}

Swift + Show Current Location and Update Location in a MKMapView

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

If you are working with iOS 8 you must include the NSLocationAlwaysUsageDescription key in info.plist file of your current project to get the location services to work.


import UIKit
import CoreLocation

import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate
{

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





        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
        
        
        let location = self.locationManager.location
        
        var latitude: Double = location.coordinate.latitude
        var longitude: Double = location.coordinate.longitude
        
        println("current latitude :: \(latitude)")
        println("current longitude :: \(longitude)")






    }

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


   You have to override CLLocationManager.didUpdateLocations (part of CLLocationManagerDelegate) to get notified when the location manager retrieves the current location:

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
    {
        //-
        
        let location = locations.last as CLLocation
        
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        
        
        self.map.setRegion(region, animated: true)
        
    
        // Add an annotation on Map View
        var point: MKPointAnnotation! = MKPointAnnotation()
        
        point.coordinate = location.coordinate
        point.title = "Current Location"
        point.subtitle = "sub title"
        
        self.map.addAnnotation(point)
        
        //stop updating location to save battery life
        locationManager.stopUpdatingLocation()

    }


//--- Uncomment to add custom annotation view ---//

    /*
    //--- use this code to add custom image (Annotation) for pin point ---//
    func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! 
{
        if !(annotation is MKPointAnnotation)
        {
            return nil
        }
        
        let reuseId = "test"
        
        var anView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId)
        
        if anView == nil
        {
            anView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
            anView.image = UIImage(named:"1.png")
            anView.canShowCallout = true
        }
        else
        {
            anView.annotation = annotation
        }
        
        return anView
    }
    */



}

Swift + NSDate ot String and Vice Versa



//--- Convert NSDate to Date String ---//

func dateformatterDate(date: NSDate) -> NSString
{
        var dateFormatter: NSDateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "MM-dd-yyyy"
        dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
        
        return dateFormatter.stringFromDate(date)
        

}





//--- Convert Date String to NSDate ---//

func dateformatterDateString(dateString: NSString) -> NSDate?
{
        var dateFormatter: NSDateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "MM-dd-yyyy"
        dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
        
        
        return dateFormatter.dateFromString(dateString)
 }

Swift + Convert Hex Color Code to UIColor By Using Extension

In viewDidLoad


self.view.backgroundColor = UIColor(hexColorCode: "#CC1800"// Solid color

self.view.backgroundColor = UIColor(hexColorCode: "#CC1800dd"// Color with alpha





//--- Add Extension on UIColor ---//

extension UIColor
{

    convenience init(hexColorCode: String)
    {
        var red:   CGFloat = 0.0
        var green: CGFloat = 0.0
        var blue:  CGFloat = 0.0
        var alpha: CGFloat = 1.0
        
        if hexColorCode.hasPrefix("#")
        {
            let index   = advance(hexColorCode.startIndex, 1)
            let hex     = hexColorCode.substringFromIndex(index)
            let scanner = NSScanner(string: hex)
            var hexValue: CUnsignedLongLong = 0
            
            if scanner.scanHexLongLong(&hexValue)
            {
                if countElements(hex) == 6
                {
                    red   = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
                    green = CGFloat((hexValue & 0x00FF00) >> 8/ 255.0
                    blue  = CGFloat(hexValue & 0x0000FF) / 255.0
                }
                else if countElements(hex) == 8
                {
                    red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
                    green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
                    blue  = CGFloat((hexValue & 0x0000FF00) >> 8/ 255.0
                    alpha = CGFloat(hexValue & 0x000000FF)         / 255.0
                }
                else
                {
                    print("invalid hex code string, length should be 7 or 9")
                }
            }
            else
            {
                println("scan hex error")
            }
        }
        else
        {
            print("invalid hex code string, missing '#' as prefix")
        }
        
        self.init(red:red, green:green, blue:blue, alpha:alpha)
    }

}




// Other Methods

extension UIColor

{
    /**
    Create non-autoreleased color with in the given hex string and alpha
    
    :param:   hexString
    :param:   alpha
    :returns: color with the given hex string and alpha
    
    
    Example:
    
    // With hash
    let color: UIColor = UIColor(hexString: "#ff8942")
    
    // Without hash, with alpha
    let secondColor: UIColor = UIColor(hexString: "ff8942", alpha: 0.5)
    
    // Short handling
    let shortColorWithHex: UIColor = UIColor(hexString: "fff")
    
    
    */
    convenience init(hexString: String, alpha: Float)
    {
        var hex = hexString
        
        // Check for hash and remove the hash
        if hex.hasPrefix("#")
        {
            hex = hex.substringFromIndex(advance(hex.startIndex, 1))
        }
        
        // Check for string length
        assert(countElements(hex) == 6 || countElements(hex) == 3)
        
        // Deal with 3 character Hex strings
        if countElements(hex) == 3
        {
            var redHex   = hex.substringToIndex(advance(hex.startIndex, 1))
            var greenHex = hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 1), end: advance(hex.startIndex, 2)))
            var blueHex  = hex.substringFromIndex(advance(hex.startIndex, 2))
            
            hex = redHex + redHex + greenHex + greenHex + blueHex + blueHex
        }
        
        let redHex = hex.substringToIndex(advance(hex.startIndex, 2))
        let greenHex = hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 2), end: advance(hex.startIndex, 4)))
        let blueHex = hex.substringWithRange(Range<String.Index>(start: advance(hex.startIndex, 4), end: advance(hex.startIndex, 6)))
        
        var redInt:   CUnsignedInt = 0
        var greenInt: CUnsignedInt = 0
        var blueInt:  CUnsignedInt = 0
        
        NSScanner(string: redHex).scanHexInt(&redInt)
        NSScanner(string: greenHex).scanHexInt(&greenInt)
        NSScanner(string: blueHex).scanHexInt(&blueInt)
        
        self.init(red: CGFloat(redInt) / 255.0, green: CGFloat(greenInt) / 255.0, blue: CGFloat(blueInt) / 255.0, alpha: CGFloat(alpha))
    }

    
    
    /**
    Create non-autoreleased color with in the given hex value and alpha
    
    :param:   hex
    :param:   alpha
    :returns: color with the given hex value and alpha
    
    Example:
    let secondColor: UIColor = UIColor(hex: 0xff8942, alpha: 0.5)
    
    */

    convenience init(hex: Int, alpha: Float)
    {
        var hexString = NSString(format: "%2X", hex)
        self.init(hexString: hexString, alpha: alpha)
    }

}