Showing posts with label iOS 8. Show all posts
Showing posts with label iOS 8. Show all posts

Monday, 2 February 2015

Objective C + Social Integration (Facebook, Twitter, Clipboard, Mail, Message, WhatsApp)

// SocialIntegration.h

#import <UIKit/UIKit.h> #import <QuartzCore/QuartzCore.h> #import <MessageUI/MessageUI.h> #import <Social/Social.h> #import <Twitter/Twitter.h> #import "WhatsAppKit.h" @interface HomeViewController : UIViewController<MFMailComposeViewControllerDelegate,MFMessageComposeViewControllerDelegate> { } -(void)openFB:(id)sender; -(void)openTW:(id)sender; -(void)copyTextIntoClipboard:(id)sender; -(void)openMail:(id)sender; -(void)openMessage:(id)sender; -(void)openWhatsApp:(id)sender; @end








// SocialIntegration.m

#define kMsgNOFbLogin @"There are no Facebook accounts configured. Please set up your Facebook account in your phone's settings." #define kMsgNOTwitterLogin @"There are no Twitter accounts configured. Please set up your Twitter account in your phone's settings." #define kError_NotSupportFeature @"Your device doesn't support this feature" // Facebook Integration - (void)openFB:(id)sender { if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) { SLComposeViewController *fbController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook]; [fbController setInitialText:@"Text Here"]; [fbController addURL:[NSURL URLWithString:@"Url String Here"]]; UIImage *image = [UIImage imageNamed:@"logo.png"]; [fbController addImage:image]; [self presentViewController:fbController animated:YES completion:nil]; [fbController setCompletionHandler:^(SLComposeViewControllerResult result) { NSString *output; switch (result) { case SLComposeViewControllerResultCancelled: output = @"Action Cancelled"; break; case SLComposeViewControllerResultDone: output = @"Message posted to your Facebook network"; break; default: break; } [self dismissViewControllerAnimated:YES completion:nil]; //check if everythink worked properly. Give out a message on the state. [self.view makeToast:output duration:3.0 position:@"center"]; }]; } else { [self.view makeToast:kMsgNOFbLogin duration:3.0 position:@"center"]; } } // Twitter Integration -(void)openTW:(id)sender { if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) { SLComposeViewController *twitterController = twitterController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter]; [twitterController setInitialText:@"Text Here"]; [twitterController addURL:[NSURL URLWithString:@"Url String Here"]]; [self presentViewController:twitterController animated:YES completion:nil]; UIImage *image = [UIImage imageNamed:@"logo.png"]; [twitterController addImage:image]; [twitterController setCompletionHandler:^(SLComposeViewControllerResult result) { NSString *output; switch (result) { case SLComposeViewControllerResultCancelled: output = @"Action Cancelled"; break; case SLComposeViewControllerResultDone: output = @"Message posted to your Twitter network"; break; default: break; } //check if everythink worked properly. Give out a message on the state. [self.view makeToast:output duration:3.0 position:@"center"]; [self dismissViewControllerAnimated:YES completion:nil]; }]; } else { [self.view makeToast:kMsgNOTwitterLogin duration:3.0 position:@"center"]; } } //Copy Text to Clipboard -(void)copyTextIntoClipboard:(id)sender { [self trackSocialShareWithLabel:@"Clipboard"]; NSString *clipboardText = @"Text Here"; UIPasteboard *pasteboard = [UIPasteboard generalPasteboard]; pasteboard.string = clipboardText; [self.view makeToast:@"Copied to clipboard" duration:3.0 position:@"center"]; } // Mail Integration -(void)openMail:(id)sender { if ([MFMailComposeViewController canSendMail]) { MFMailComposeViewController *mailComposeViewController = [[MFMailComposeViewController alloc] init]; mailComposeViewController.mailComposeDelegate = self; [mailComposeViewController setSubject:@"Smart Shop"]; //NSArray *toRecipients = [NSArray arrayWithObject:@""]; [mailComposeViewController setToRecipients:nil]; NSString *emailBody = [NSString stringWithFormat:@"%@\n%@",kSharedSocialString,kSharedUrlString]; [mailComposeViewController setMessageBody:emailBody isHTML:NO]; mailComposeViewController.navigationBar.barStyle = UIBarStyleBlackOpaque; [self presentViewController:mailComposeViewController animated:YES completion:nil]; } else { [self.view makeToast:kError_NotSupportFeature duration:3.0 position:@"center"]; } } #pragma mark- MFMailComposeViewControllerDelegate Method:: - (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error { [self dismissViewControllerAnimated:YES completion:nil]; } // Message Integration -(void)openMessage:(id)sender { [self trackSocialShareWithLabel:@"Message"]; if(![MFMessageComposeViewController canSendText]) { [self.view makeToast:kError_NotSupportFeature duration:3.0 position:@"center"]; return; } else { MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init]; picker.messageComposeDelegate = self; picker.recipients = nil; NSString *msgBody = [NSString stringWithFormat:@"%@\n%@",kSharedSocialString,kSharedUrlString]; picker.body = msgBody; [self presentViewController:picker animated:YES completion:nil]; } } #pragma mark- MFMessageComposeViewControllerDelegate Method:: - (void)messageComposeViewController:(MFMessageComposeViewController *)controller didFinishWithResult:(MessageComposeResult) result { switch (result) { case MessageComposeResultCancelled: break; case MessageComposeResultFailed: { [self.view makeToast:@"Failed to send SMS!" duration:3.0 position:@"center"]; break; } case MessageComposeResultSent: break; default: break; } [self dismissViewControllerAnimated:YES completion:nil]; } // WhatsApp Integration
-(void)openWhatsApp:(id)sender { if ([WhatsAppKit isWhatsAppInstalled]) { [WhatsAppKit launchWhatsAppWithMessage:@""]; } else { [self.view makeToast:kError_NotSupportFeature duration:3.0 position:@"center"]; } }



Objective C + Parse Json From Bundle

NSMutableArray *arrayAdventureList = [self dataFromJSONFileNamed:@"Adventure"]; -(NSMutableArray *)dataFromJSONFileNamed:(NSString *)fileName { NSString *filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"json"]; NSData *fileData = [NSData dataWithContentsOfFile:filePath]; NSError *error = nil; NSMutableDictionary *dicAdventureList = [NSJSONSerialization JSONObjectWithData:fileData options:kNilOptions error:&error]; return [dicAdventureList objectForKey:@"adventure_list"]; }

Objective C + XML/SOAP

// .h File

#import <UIKit/UIKit.h> @interface ViewController : UIViewController<NSURLConnectionDataDelegate,NSURLConnectionDelegate,NSXMLParserDelegate> { NSString *curDescription; } @property (strong, nonatomic) NSMutableData *webResponseData; @end


// .m File

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NSString *soapMessage = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" "<soap:Body>" "<CelsiusToFahrenheit xmlns=\"http://www.w3schools.com/webservices/\">" "<Celsius>50</Celsius>" "</CelsiusToFahrenheit>" "</soap:Body>" "</soap:Envelope>"; NSString *soapMessage1 = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" "<soap:Body>" "<CelsiusToFahrenheit xmlns=\"http://www.w3schools.com/webservices/\">" "<Celsius>%@</Celsius>" "</CelsiusToFahrenheit>" "</soap:Body>" "</soap:Envelope>" ,@"50"]; NSURL *requestURL = [NSURL URLWithString:@"http://www.w3schools.com/webservices/tempconvert.asmx"]; NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:requestURL]; NSString *messageLength = [NSString stringWithFormat:@"%d", (int)[soapMessage length]]; [myRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [myRequest addValue: @"http://www.w3schools.com/webservices/CelsiusToFahrenheit" forHTTPHeaderField:@"SOAPAction"]; [myRequest addValue: messageLength forHTTPHeaderField:@"Content-Length"]; [myRequest setHTTPMethod:@"POST"]; [myRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self]; if( theConnection ) { self.webResponseData = [NSMutableData data]; } else { NSLog(@"Some error occurred in Connection"); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma marks- NSUrlConnection Delegate Methods Implementation:: -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [self.webResponseData setLength:0]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.webResponseData appendData:data]; } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"Some error in your Connection. Please try again."); } -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"Received Bytes from server: %d", (int)[self.webResponseData length]); NSString *myXMLResponse = [[NSString alloc] initWithBytes: [self.webResponseData bytes] length:[self.webResponseData length] encoding:NSUTF8StringEncoding]; NSLog(@"myXMLResponse :: %@",myXMLResponse); // Parse XML NSData *myData = [myXMLResponse dataUsingEncoding:NSUTF8StringEncoding]; NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:myData]; // Don't forget to set the delegate! xmlParser.delegate = self; // Run the parser BOOL parsingResult = [xmlParser parse]; } #pragma mark - NSXMLParserDelaget Implementation :: -(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { } - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string { curDescription = string; } - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName { if([elementName isEqual: @"CelsiusToFahrenheitResult"]) NSLog(@"curDescription :: %@",curDescription); }

Sunday, 28 December 2014

Swift + Get Height of Label Dynamically

func heightForLabel(text:String, font:UIFont, width:CGFloat) -> CGFloat
    {
        let label:UILabel = UILabel(frame: CGRectMake(0, 0, width, CGFloat.max))
        label.numberOfLines = 0
        label.lineBreakMode = NSLineBreakMode.ByWordWrapping
        label.font = font
        label.text = text
        
        label.sizeToFit()
        return label.frame.height

    }




let font = UIFont(name: "Verdana", size: 12)
        var detailHeight = heightForLabel("Your String", font: font!, width: self.scrollView.bounds.size.width-10)

Thursday, 18 December 2014

Objective C + Calculate Height of Table's Cell Dynamically or At Run Time



// TableView Delegate Method
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    int width = 300; // width of your label
    
    return ([Self calculateHeightOfString:@"Your String" withFont:[UIFont systemFontOfSize:15] ofWidth:width withLineBreak:NSLineBreakByWordWrapping]+30);
    

}




// Method to calculate height
-(float)calculateHeightOfString:(NSString *)str withFont:(UIFont *)font ofWidth:(float)width withLineBreak:(NSLineBreakMode)line
{
    //NSLog(@"%s",__PRETTY_FUNCTION__);
  
CGSize suggestedSize = [str sizeWithFont:font constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:line];

return suggestedSize.height;

}

Objective C + Open UIDatePicker with ActionSheet



// In .h file
UIDatePicker *datePicker;



[self showDatePicker: UIDatePickerModeDate];
                              or
[self showDatePicker: UIDatePickerModeTime];






// Method to show DatePicker on ActionSheet
-(void) showDatePicker: (UIDatePickerMode) modeDatePicker
{
    
    UIView *viewDatePicker = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
    [viewDatePicker setBackgroundColor:[UIColor clearColor]];
    
    //Make a frame for the picker & then create the picker
    CGRect pickerFrame = CGRectMake(0, 0, self.view.frame.size.width, 200);
    datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
    
    datePicker.datePickerMode = modeDatePicker;
    datePicker.hidden = NO;
    [viewDatePicker addSubview:datePicker];
    
    
    if([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                                 message:@"\n\n\n\n\n\n\n\n\n\n"
                                                                          preferredStyle:UIAlertControllerStyleActionSheet];
        
        [alertController.view addSubview:viewDatePicker];
        
        
        
        UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action)
                                     {
                                         //Detect particular click by tag and do some thing here

                                         if(tagDateField == 0 || tagDateField == 2)
                                         {
                                             [self setSelectedDateInField];
                                         }
                                         else if (tagDateField == 1 || tagDateField == 3)
                                         {
                                             [self setSelecteedTimeInField];
                                         }
                                         
                                         
                                         NSLog(@"OK action");
                                         
                                     }];
        [alertController addAction:doneAction];
        
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action)
                                       {
                                           NSLog(@"Cancel action");
                                       }];
        
        
        
        [alertController addAction:cancelAction];
        
        /*
         UIAlertAction *resetAction = [UIAlertAction
         actionWithTitle:NSLocalizedString(@"Reset", @"Reset action")
         style:UIAlertActionStyleDestructive
         handler:^(UIAlertAction *action)
         {
         NSLog(@"Reset action");
         }];
         
         [alertController addAction:resetAction];
         */
        
        
        [self presentViewController:alertController animated:YES completion:nil];
        
        
        
    }
    else
    {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"\n\n\n\n\n\n\n\n\n\n" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Done" otherButtonTitles:nil, nil];
        [actionSheet addSubview:viewDatePicker];
        [actionSheet showInView:self.view];
        
    }
    
}



// Methods to set selected date and time in related field

-(void)setSelectedDateInField
{
    NSLog(@"date :: %@",datePicker.date.description);
    
    
    //set Date formatter
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
    [formatter1 setDateFormat:@"MM/dd/YY"];
    
    if(tagDateField == 0)
    {
        [txtExpirationDate setText:[formatter1 stringFromDate:datePicker.date]];
        
    }
    else if (tagDateField == 2)
    {
        [txtBeginDate setText:[formatter1 stringFromDate:datePicker.date]];
    }
    
}


-(void)setSelecteedTimeInField
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"HH:mm"];
    
    if (tagDateField == 3)
    {
        [txtBeginTime setText:[dateFormatter stringFromDate:datePicker.date]];
    }
    else if (tagDateField == 1)
    {
        [txtExpirationTime setText:[dateFormatter stringFromDate:datePicker.date]];
    }

}









// Action sheet Delegate In case of iOS 7
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        if(tagDateField == 0 || tagDateField == 2)
        {
            [self setSelectedDateInField];
        }
        else if (tagDateField == 1 || tagDateField == 3)
        {
            [self setSelecteedTimeInField];
        }

    }
}



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: UIViewController, UIImagePickerControllerDelegate, UIAlertViewDelegate, UINavigationControllerDelegate
{

    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: UIViewController, CLLocationManagerDelegate
{

    @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: UIViewController, CLLocationManagerDelegate
{

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




}