Sunday, 5 February 2017

How to create UIDatePicker in swift - Tutorial




UIDatePicker Swift3 Tutorial

Introduction to UIDatePicker in Swift

UIDatepicker is the control provided by UIKit framework packaged with xcode IDE. It allows user to pick date from the spinning wheel that act same as drop down option in web. You can use UIDatePicker in your app where you want to allow user to enter or input
  • a Date
  • both Date and Time
  • only Time
  • Countdown timer

Steps to create UIDatePicker in swift

Step 1: Create a new xcode project and name it UIDatePicker-Swift, if you are not familiar with creating xcode project you can check here

Step 2: Open Main.storyboard and drag UIDatePicker on to the view.

UIDatePicker-added-to-the-view
UIDatePicker added to the view
Step 3: Add constraint to UIDatePicker. Shown in the image below

Add-constraints-to-UIDatePicker
Add constraints to UIDatePicker

Step 4: Open ViewController.swift and create an IBOutlet to UIDatePicker

  
  @IBOutlet weak var datePicker: UIDatePicker!


Step 5: Open Main.storyboard and connect our IBOutlet created in step 3 to the UIDatePicker placed on the view as shown in the image below

Connecting-IBOutlet-to-UIDatePicker
Connecting IBOutlet to UIDatePicker
Step 6: Set current date as our UIDatePicker date, so that when screen launches/shown to the user it display current date as selected date


  override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.datePicker.date = NSDate.init(timeIntervalSinceNow: 0) as Date
 }

Step 7: Run your code, you will see UIDatePicker showing current date as selected date.

Get selected date from UIDatePicker

Till now you created UIDatePicker successfully, now the question is  how can we get date selected by user. For this we can do two things

  • will add a button and add IBAction to it so that when user tap on button we will get our selected date. 
  • Add our IBAction to UIDatePicker and assign it to ValueChanged event, so that whenever UIDatePicker date changed it notifies us
Step 8: Open Main.storyboard and add UIButton to it. Add constraint to it as shown in below image

Adding constraints to UIButton
Adding constraints to UIButton
Step 9: Open ViewController.swift and create our IBActions, one for 
  • Button Tap event 
  • UIDatePicker value change event
Below is the code that solve our purpose in both ways


   @IBAction func doneWithDateSelection(_ sender :AnyObject) {
        print("Date Selected through button  == ", datePicker.date)
    }
    
    @IBAction func pickerDateSelectionChanged(_ sender :AnyObject) {
        print("Date Selected via UIDatePicker value change == ", datePicker.date)
    }


Step 10:  Open Main.storyboard and add IBaction to UIButton and UIDatePicker as shown below

Connecting IBAction to UIButton
Connecting IBAction to UIButton
Connecting IBAction to UIDatePicker
Connecting IBAction to UIDatePicker
Step 11: Run your app and you will see date in console when you tap on Button or change UIDatePicker value.

Step 12: If you see your date on console, you will get time also. In order to get only you have to get date with dateformatter class given by xcode. Below is the complete code that

Complete code which print date only when user tap on button or change date picker value

Complete Code


 //
//  ViewController.swift
//  UIDatePicker-Swift
//
//  Created by Aman Aggarwal on 12/21/16.
//  Copyright © 2016 iostutorialjunction. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var datePicker: UIDatePicker!
    var dateFormatter = DateFormatter()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.datePicker.date = NSDate.init(timeIntervalSinceNow: 0) as Date
        dateFormatter.dateFormat = "MM/dd/yyyy"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func doneWithDateSelection(_ sender :AnyObject) {
        
        print("Date Selected through button  == ", dateFormatter.string(from: datePicker.date))
    }

    @IBAction func pickerDateSelectionChanged(_ sender :AnyObject) {
        print("Date Selected via UIDatePicker value change== ", dateFormatter.string(from: datePicker.date))
    }
    
}

Where to go from here

In this tutorial you learned about UIDatePicker in swift and how to print/select date form UIDatePicker without time using dateformatter. You can get the whole code sample from here .
If you have any concerns than you can comment here. Happy Coding :)






Sunday, 15 January 2017

programmatically share image to Instagram through iOS app

Post image to Instagram programmatically in iOS app - tutorial

Introduction to the post programmatically share image to Instagram through iOS app

Instagram is another most popular social platform for sharing images. Now days, every app share image to Instagram too. Since like other social platforms Instagram does not provide developers permission to write image directly on the user Instagram wall. So for this we can use UIDocumentInteractionController provided in objective c and swift language in X-code.

For sharing/posting image to Instagram, you should have two things
1.  Instagram should be installed on your device.
2.  User must be logged-in onto Instagram app prior to sharing/Posting image.

NOTE:- If user is not logged in then you have to log him/her in first and then allow him to open your app and re share it.

Code for sharing image to Instagram through iOS app - objective C



Code for sharing image to Instagram through iOS app - Swift 3


  
For sharing image to Instagram, first we created an image with extension .igo(its instagram file extension so that the Instagram app can be shown in UIDocumentController) then save it to our document directory by first removing any image the already written on that location and re writing new image using writeToFile method, that we are going to share to Instagram. Then we will create our UIDocumentController instance and gave it the path of our sharing image that we wrote in document directory. After finish this, we have to specify app identifier to let compiler know which app is capable of opening .igo type document, here we gave "com.instagram.exclusivegram". Lastly, we present our UIDocumentController to user.


How to integrate Push Notification in iOS 10 - Tutorial



Push Notification iOS 10 Tutorial

 INTRODUCTION to the post how to integrate Push Notification in iOS 10 - Tutorial :

In this post we will learn how to use Push notification in iOS 10. With iOS 10 there are lots of changes push notification implementation. The new framework called "UserNotifications.framework" will supports the delivery and handling of push notification in iOS 10 and onward.

With iOS 10, we can also display notification from top in foreground state same as showed by iOS when app is in background state i.e. default notification pop up on top of iPhone/iPad screen,

Implementation of code

Follow below steps to implement code to handle push notification in iOS 10.

Step 1: Import UserNotifications.framework in AppDelegate.m file


#import < UserNotifications/UserNotifications.h >


Step 2: Add UNUserNotificationCenterDelegate, telling our class that we are going to implement UNUserNotificationDelegates


@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end


Step 3: Register for push notification in order to get device token. If your app target to iOS below iOS 10 then you have to place check to handle it.


if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")){
        
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        
        center.delegate = self;
        
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadgecompletionHandler:^(BOOL granted, NSError * _Nullable error){
            
            if(!error){
                
                [[UIApplication sharedApplicationregisterForRemoteNotifications];
                
            }
            
        }]; 
        
    }
    else {

            //for iOS8

}


Note: SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v) is the constant as given below


#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)


Step 4: It's time to implement delegate methods of UNUserNotificationDelegates


//Called when a notification is delivered to a foreground app.

-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{
    
    NSLog(@"User Info : %@",notification.request.content.userInfo);
    
    completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge);
    
}

//Called to let your app know which action was selected by the user for a given notification.

-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{
    
    NSLog(@"User Info : %@",response.notification.request.content.userInfo);
    
    completionHandler();
    
}


Step 5: Add push notification entitlements. This will get configured if you properly set up the profile for the push notification capability.Below is the image that showed from where it will gets automatically added to your app.

Turn-on-Push-notification-capabilities-for teh-app-that-will-add-entitlements-file-automatically



Sunday, 1 January 2017

How to enable Push Notification service for iOS app in Apple Developer account

 
Setup Push Notification in Apple Developer account

Introduction:

In order to implement Push Notification in iOS app, developer must have to enable push notification service for the app id/ bundle identifier (app identifier). In this tutorial we learn how to enable push notification service for the app id in  Apple Developer Account

Steps to enable push services for your iOS App in Apple Developer account:

Follow below steps to setup Push Notification in Apple Developer Account

Step 1: Log in to Apple Developer Account  and  click Certificates, identifiers and Profile.

Step 2: Select App IDs under identifiers tab and click on plus button. 

Create New App ID

 Step 3: Name your App ID under App ID Description and Bundle ID under App ID Suffix as shown in the image.

Name App ID and Bundle ID

Step 4: Scroll down and check mark the checkbox against Push Notification under App Services.

Select Push Notification App service

Step 5: Press register and you are done with enabling push notification for your app id. Still we have to configure the SSL certificates. In next steps we will learn how to create SSL certificates. 

Step 6: Select App IDs under identifiers tab and click on the App ID created by us in previous steps. In our case it is named as PushNotificationTutorial. Click on it and you will see detail services offered by the App ID. Click on Edit button at the bottom.

Services offered by App ID

Step 7: Navigate to the portion of page as shown in below image.

Create SSL certificates for Push Notification

Step 8: Follow Create Push certificates tutorial to create push certificates.

Where to Go From Here?

In this post we learn How to setup Push Notification service in Apple Developer account. After setting up push notification service for our App ID, it's time to create .pem file so that your app can receive push from Apple push server.

http://www.iostutorialjunction.com/2016/11/How-to-create-or-generate-.pem-file-for-push-notification-Tutorial.html

Sunday, 18 December 2016

How to create NSMutableAttributedString in swift 3 - Tutorial IOS



NSMutableAttributedString_Swift_Tutorial_swift3.0

Introduction to NSMutableAttributedString in swift:

NSMutableAttributedString is a great way to customize or decorate UILable text programmatically. For example your requirement involves certain word in the middle of the text is in bold and in different color, what will you do. In this case one can use NSMutableAttributedString class provided in swift language. In this post we will learn different attributes of NSMutableAttributedString .

Implementation of code:

Let us start by creating an new project by choosing single view application template and select development language as SWIFT/swift3, name your project NSMutableAttributedString-Tutorial.

Open ViewController.swift class create your IBOutlet for UILable


    @IBOutlet var strLable : UILabel?


Open main.storyboard and drag and UILable to it. Connect your strLable to UILable dragged on to the view.

Open ViewController.swift file and inside our viewDidLoad method we will create our NSMutableAttributedString.

  
 let stringAttributed = NSMutableAttributedString.init(string: "If already have  account, please Login")

     
In the above string we will highlight "Login"by making it bold and green color string.To achieve this we have to add attribute to our attributed string. Assign out NSMutableAttributedString to our table.

  
let font = UIFont(name: "verdana-bold", size: 18.0)
stringAttributed.addAttribute(NSFontAttributeName, value:font!, range: NSRange.init(location: 32, length: 5))
        stringAttributed.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange.init(location: 32, length: 5))


        strLable?.attributedText = stringAttributed;


Run your code, you will see output like the below image


NSMutableAttributedString_Swift_tutorial

Underline Attribute:


let font = UIFont(name: "verdana-bold", size: 18.0)
        stringAttributed.addAttribute(NSFontAttributeName, value:font!, range: NSRange.init(location: 32, length: 5))
        stringAttributed.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange.init(location: 32, length: 5))
        stringAttributed.addAttribute(NSUnderlineStyleAttributeName, value: 1.0, range: NSRange.init(location: 32, length: 5))

        strLable?.attributedText = stringAttributed;


Run your code, you will see output like the below image
NSMutableAttributedString_Swift_Tutorial_underlineStyle

Background color Attribute:



let font = UIFont(name: "verdana-bold", size: 18.0)
        stringAttributed.addAttribute(NSFontAttributeName, value:font!, range: NSRange.init(location: 32, length: 5))
        stringAttributed.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange.init(location: 32, length: 5))
        stringAttributed.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(), range: NSRange.init(location: 0, length: stringAttributed.length))
        strLable?.attributedText = stringAttributed;


Run your code, you will see output like the below image

NSMutableAttributedString_Swift_Tutorial_BackgroundColorAttribute

Stroke color Attribute and stroke width attribute:



 let font = UIFont(name: "verdana-bold", size: 18.0)
        stringAttributed.addAttribute(NSFontAttributeName, value:font!, range: NSRange.init(location: 32, length: 5))
        stringAttributed.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange.init(location: 32, length: 5))
        stringAttributed.addAttribute(NSStrokeColorAttributeName, value: UIColor.redColor(), range: NSRange.init(location: 0, length: stringAttributed.length))
        stringAttributed.addAttribute(NSStrokeWidthAttributeName, value: 2.0, range: NSRange.init(location: 0, length: stringAttributed.length))
        strLable?.attributedText = stringAttributed;


Run your code, you will see output like the below image

NSMutableAttributedString_Swift_Tutorial_storeColorattribute_strokeWidthAttribute

Final comments:

In above tutorial we learned  some of the attributes provided by NSMutableAttributedString in swift language. Hope this helps you win learning NSMutableAttributedString in swift and in decorating your text headlines in the iOS app. Stay tuned for more tutorials on swift.