Thursday, July 27, 2017

DOWNPICKER


Downpicker:


#import "DownPicker.h"
@interface HoursViewController ()<UITextFieldDelegate,getValueDelegate,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic) DownPicker *picker;
@property (nonatomic) DownPicker *picker1;

 self.picker = [[DownPicker alloc] initWithTextField:self.hourstextfield withData:array];
    self.picker.delegate = self;
    self.hourstextfield.text = [NSString stringWithFormat:@"%@",array[0]];
  
    NSArray *e1 = @[@"Select City",@"Vancouver",@"Burnaby"];
    self.picker1 = [[DownPicker alloc] initWithTextField:self.citytextfield withData:e1];
    self.citytextfield.text = e1[0];

DownPicker.m

//
//   DownPicker.h
// --------------------------------------------------------
//      Lightweight DropDownList/ComboBox control for iOS
//
// by Darkseal, 2013-2015 - MIT License
//
// Website: http://www.ryadel.com/
// GitHub:  http://www.ryadel.com/
//


#import "DownPicker.h"

@implementation DownPicker
{
    NSString* _previousSelectedString;
}

-(id)initWithTextField:(UITextField *)tf
{
    return [self initWithTextField:tf withData:nil];
}

-(id)initWithTextField:(UITextField *)tf withData:(NSArray*) data
{
    self = [super init];
    if (self) {
        self->textField = tf;
        self->textField.delegate = self;
      
        // set UI defaults
        self->toolbarStyle = UIBarStyleDefault;
      
        // set language defaults
        self->placeholder = @"Anytime ";
       
        self->placeholderWhileSelecting = @"Pick an option...";
        self->toolbarDoneButtonText = @"Done";
        self->toolbarCancelButtonText = @"Cancel";
       
        // hide the caret and its blinking
        [[textField valueForKey:@"textInputTraits"]
         setValue:[UIColor clearColor]
         forKey:@"insertionPointColor"];
       
        // set the placeholder
        self->textField.placeholder = self->placeholder;
//        textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:self->placeholder attributes:@{NSForegroundColorAttributeName: [UIColor colorWithCGColor:[UIColor colorWithHexString:@"5c5c5c"].CGColor]}];

       
        // setup the arrow image
        UIImage* img = [UIImage imageNamed:@"downArrow.png"];   // non-CocoaPods
        if (img == nil) img = [UIImage imageNamed:@"DownPicker.bundle/downArrow.png"]; // CocoaPods
        if (img != nil) self->textField.rightView = [[UIImageView alloc] initWithImage:img];
        self->textField.rightView.contentMode = UIViewContentModeScaleAspectFit;
        self->textField.rightView.clipsToBounds = YES;
       
        // show the arrow image by default
        [self showArrowImage:YES];

        // set the data array (if present)
        if (data != nil) {
            [self setData: data];
        }
       
        self.shouldDisplayCancelButton = YES;
    }
    return self;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    self->textField.text = [dataArray objectAtIndex:row];
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
{
    return [dataArray count];
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
{
    return [dataArray objectAtIndex:row];
}

-(void)doneClicked:(id) sender
{
       
    //hides the pickerView
    [textField resignFirstResponder];
   
    if (self->textField.text.length == 0 || ![self->dataArray containsObject:self->textField.text]) {
        // self->textField.text = [dataArray objectAtIndex:0];
        [self setValueAtIndex:-1];
        self->textField.placeholder = self->placeholder;
    }
    /*
    else {
        if (![self->textField.text isEqualToString:_previousSelectedString]) {
            [self sendActionsForControlEvents:UIControlEventValueChanged];
        }
    }
    */
   
    [self.delegate selectionValue:self->textField.text preString:_previousSelectedString];

    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

-(void)cancelClicked:(id)sender
{
    [textField resignFirstResponder]; //hides the pickerView
    if (_previousSelectedString.length == 0 || ![self->dataArray containsObject:_previousSelectedString]) {
        self->textField.placeholder = self->placeholder;
    }
    self->textField.text = _previousSelectedString;
}

- (IBAction)showPicker:(id)sender
{
    _previousSelectedString = self->textField.text;
   
    pickerView = [[UIPickerView alloc] init];
    pickerView.showsSelectionIndicator = YES;
    pickerView.dataSource = self;
    pickerView.delegate = self;
   
   
    //If the text field is empty show the place holder otherwise show the last selected option
    if (self->textField.text.length == 0 || ![self->dataArray containsObject:self->textField.text])
    {
        if (self->placeholderWhileSelecting) {
            self->textField.placeholder = self->placeholderWhileSelecting;
        }
        // 0.1.31 patch: auto-select first item: it basically makes placeholderWhileSelecting useless, but
        // it solves the "first item cannot be selected" bug due to how the pickerView works.
        [self setSelectedIndex:0];
    }
    else
    {
        if ([self->dataArray containsObject:self->textField.text]) {
            [self->pickerView selectRow:[self->dataArray indexOfObject:self->textField.text] inComponent:0 animated:YES];
        }
    }

    UIToolbar* toolbar = [[UIToolbar alloc] init];
    toolbar.barStyle = self->toolbarStyle;
    [toolbar sizeToFit];
   
    //space between buttons
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
   
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc]
                                   initWithTitle:self->toolbarDoneButtonText
                                   style:UIBarButtonItemStyleDone
                                   target:self
                                   action:@selector(doneClicked:)];
   
    if (self.shouldDisplayCancelButton) {
        UIBarButtonItem* cancelButton = [[UIBarButtonItem alloc]
                                         initWithTitle:self->toolbarCancelButtonText
                                         style:UIBarButtonItemStylePlain
                                         target:self
                                         action:@selector(cancelClicked:)];
       
        [toolbar setItems:[NSArray arrayWithObjects:cancelButton, flexibleSpace, doneButton, nil]];
    } else {
        [toolbar setItems:[NSArray arrayWithObjects:flexibleSpace, doneButton, nil]];
    }


    //custom input view
    textField.inputView = pickerView;
    textField.inputAccessoryView = toolbar; 
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)aTextField
{
    if ([self->dataArray count] > 0) {
        [self showPicker:aTextField];
        return YES;
    }
    return NO;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self sendActionsForControlEvents:UIControlEventEditingDidBegin];
}

- (void)textFieldDidEndEditing:(UITextField *)aTextField {
    // [self doneClicked:aTextField];
    aTextField.userInteractionEnabled = YES;
    [self sendActionsForControlEvents:UIControlEventEditingDidEnd];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    return NO;
}

-(void) setData:(NSArray*) data
{
    dataArray = data;
}

-(void) showArrowImage:(BOOL)b
{
    if (b == YES) {
      // set the DownPicker arrow to the right (you can replace it with any 32x24 px transparent image: changing size might give different results)
        self->textField.rightViewMode = UITextFieldViewModeAlways;
    }
    else {
        self->textField.rightViewMode = UITextFieldViewModeNever;
    }
}

-(void) setArrowImage:(UIImage*)image
{
    [(UIImageView*)self->textField.rightView setImage:image];
}

-(void) setPlaceholder:(NSString*)str
{
    self->placeholder = str;
    self->textField.placeholder = self->placeholder;
}

-(void) setPlaceholderWhileSelecting:(NSString*)str
{
    self->placeholderWhileSelecting = str;
}

-(void) setAttributedPlaceholder:(NSAttributedString *)attributedString
{
    self->textField.attributedPlaceholder = attributedString;
}

-(void) setToolbarDoneButtonText:(NSString*)str
{
    self->toolbarDoneButtonText = str;
}

-(void) setToolbarCancelButtonText:(NSString*)str
{
    self->toolbarCancelButtonText = str;
}

-(void) setToolbarStyle:(UIBarStyle)style;
{
    self->toolbarStyle = style;
}

-(UIPickerView*) getPickerView
{
    return self->pickerView;
}

-(UITextField*) getTextField
{
    return self->textField;
}

-(NSString*) getValueAtIndex:(NSInteger)index
{
    return (self->dataArray.count > index) ? [self->dataArray objectAtIndex:index] : nil;
}

-(void) setValueAtIndex:(NSInteger)index
{
    if (index >= 0) [self pickerView:nil didSelectRow:index inComponent:0];
    else [self setText:nil];
}

/**
 Getter for text property.
 @return
 The value of the selected item or NIL NIL if nothing has been selected yet.
 */
- (NSString*) text {
    return self->textField.text;
}

/**
 Setter for text property.
 @param txt
 The value of the item to select or NIL to clear selection.
 */
- (void) setText:(NSString*)txt {
    if (txt != nil) {
        NSInteger index = [self->dataArray indexOfObject:txt];
        if (index != NSNotFound) [self setValueAtIndex:index];
    }
    else {
        self->textField.text = txt;
    }
}

/**
 Getter for selectedIndex property.
 @return
 The zero-based index of the selected item or -1 if nothing has been selected yet.
 */
- (NSInteger)selectedIndex {
    NSInteger index = [self->dataArray indexOfObject:self->textField.text];
    return (index != NSNotFound) ? (NSInteger)index : -1;
}

/**
 Setter for selectedIndex property.
 @param index
 Sets the zero-based index of the selected item using the setValueAtIndex method: -1 can be used to clear selection.
 */
- (void)setSelectedIndex:(NSInteger)index {
    [self setValueAtIndex:(NSInteger)index];
}

@end

//
//   DownPicker.h
// --------------------------------------------------------
//      Lightweight DropDownList/ComboBox control for iOS
//
// by Darkseal, 2013-2015 - MIT License
//
// Website: http://www.ryadel.com/
// GitHub:  http://www.ryadel.com/
//

#import <UIKit/UIKit.h>
#import "UIColor+Hex.h"
@class HeaderView;

@protocol getValueDelegate <NSObject>
@optional
- (void)selectionValue :(NSString *)selection preString:(NSString *)prevStr;
@end

@interface DownPicker : UIControl<UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate,getValueDelegate>
{
    UIPickerView* pickerView;
    IBOutlet UITextField *textField;
    NSArray* dataArray;
    NSString* placeholder;
    NSString* placeholderWhileSelecting;
    NSString* toolbarDoneButtonText;
    NSString* toolbarCancelButtonText;
    UIBarStyle toolbarStyle;
}

@property (nonatomic, weak) id <getValueDelegate> delegate;

@property (nonatomic) NSString* text;
@property (nonatomic) NSInteger selectedIndex;


-(id)initWithTextField:(UITextField *)tf;
-(id)initWithTextField:(UITextField *)tf withData:(NSArray*) data;

@property (nonatomic) BOOL shouldDisplayCancelButton;

/**
 Sets an alternative image to be show to the right part of the textbox (assuming that showArrowImage is set to TRUE).
 @param image
 A valid UIImage
 */
-(void) setArrowImage:(UIImage*)image;

-(void) setData:(NSArray*) data;
-(void) setPlaceholder:(NSString*)str;
-(void) setPlaceholderWhileSelecting:(NSString*)str;
-(void) setAttributedPlaceholder:(NSAttributedString *)attributedString;
-(void) setToolbarDoneButtonText:(NSString*)str;
-(void) setToolbarCancelButtonText:(NSString*)str;
-(void) setToolbarStyle:(UIBarStyle)style;

/**
 TRUE to show the rightmost arrow image, FALSE to hide it.
 @param b
 TRUE to show the rightmost arrow image, FALSE to hide it.
 */
-(void) showArrowImage:(BOOL)b;

-(UIPickerView*) getPickerView;
-(UITextField*) getTextField;

/**
 Retrieves the string value at the specified index.
 @return
 The value at the given index or NIL if nothing has been selected yet.
 */
-(NSString*) getValueAtIndex:(NSInteger)index;

/**
 Sets the zero-based index of the selected item: -1 can be used to clear selection.
 */
-(void) setValueAtIndex:(NSInteger)index;
@end
 

Webservice with nsurlsession

App Delegate:

#import <UIKit/UIKit.h>
#import "ASIFormDataRequest.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate,ASIHTTPRequestDelegate>
{
    ASIFormDataRequest *serverRequest;
    NSString *urlType;
    UIView *spinerView;
    UIActivityIndicatorView *activityView;
}
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic,strong)ASIFormDataRequest *serverRequest;
-(void)PostWebServer:(NSMutableDictionary *)dict type:(NSString *)webServive;
-(void)showView;
-(void)hideView;
@end

AppDelegate.m


#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    return YES;
}
-(void)PostWebServer:(NSMutableDictionary *)dict type:(NSString *)webServive
{
    if(serverRequest)
    {
        [self.serverRequest cancel];
        [self.serverRequest clearDelegatesAndCancel];
    }
    urlType=webServive;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *strurl=[NSString stringWithFormat:@"%@",webServive];
    NSURL *url=[NSURL URLWithString:strurl];
    NSLog(@"WEB SERVICE URL------%@",url);
    serverRequest=[ASIFormDataRequest requestWithURL:url];
    [serverRequest setPostBody:[NSMutableData dataWithData:jsonData]];
    [serverRequest setRequestMethod:@"POST"];
    [serverRequest setDelegate:self];
    [serverRequest startAsynchronous];
}
-(void)showView
{
    if ([[UIScreen mainScreen] bounds].size.height==568)
    {
        spinerView=[[UIView alloc] initWithFrame:CGRectMake(110, 240, 100, 100)];
    }
    else if([[UIScreen mainScreen] bounds].size.height==480)
    {
        spinerView=[[UIView alloc] initWithFrame:CGRectMake(110, 200, 100, 100)];
    }
    else
    {
        spinerView=[[UIView alloc] initWithFrame:CGRectMake(135, 270, 100, 100)];
    }
    spinerView.backgroundColor=[UIColor lightGrayColor];
    spinerView.layer.cornerRadius=8;
    self.window.userInteractionEnabled=NO;
    [self.window addSubview:spinerView];
    activityView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityView.frame=CGRectMake(35, 30, 25, 25);
   
    UILabel *loading=[[UILabel alloc] initWithFrame:CGRectMake(15, 55, 100, 20)];
    loading.backgroundColor=[UIColor clearColor];
    loading.text=@"Loading";
    loading.textColor=[UIColor whiteColor];
    [spinerView addSubview:loading];
    [spinerView addSubview:activityView];
    [activityView startAnimating];
}

-(void)hideView
{
    self.window.userInteractionEnabled=YES;
    [spinerView removeFromSuperview];
}

-(void)requestFinished:(ASIHTTPRequest *)request{
    NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:[request responseData] options:0 error:nil];
    [[NSNotificationCenter defaultCenter]postNotificationName:urlType object:self userInfo:dict];
}

-(void)requestFailed:(ASIHTTPRequest *)request{ 
}

ViewController:

#import <UIKit/UIKit.h>
#import "AppDelegate.h"

@interface ViewController : UIViewController<UITextFieldDelegate>
{
    AppDelegate *delObj;

}
@property(nonatomic,retain)IBOutlet UITextField *usernameTextfield;
@property(nonatomic,retain)IBOutlet UITextField *passwordTextfield;
-(IBAction)MatchApiRequest:(id)sender;

@end

viewcontroller.m

#import "ViewController.h"
#import "Reachability.h"
#import "DetailViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    delObj=(AppDelegate *)[[UIApplication sharedApplication] delegate];

}
-(IBAction)MatchApiRequest:(id)sender
{
   
    if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Network Error" message:@"Please check your internet connection, try again" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        alert.tag=100;
        [alert show];
    }
    else
    {
        //connection available
       
        [delObj showView];
       
        [[NSNotificationCenter defaultCenter]removeObserver:self name:@"http://aiv2.ibbtrade.com/login" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMatchingResponse:) name:@"http://aiv2.ibbtrade.com/login" object:nil];
        NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
//        [dict setValue:self.usernameTextfield.text forKey:@"uName"];
//        [dict setValue:self.passwordTextfield.text forKey:@"pWord"];
        dict=@{@"username":@"valuator1",@"password":@"1234567",@"client_id":@"autoinsp",@"client_secret":@"test@123",@"ip":@"172.16.24.82",@"simno":@"7849ecbba6dde263",@"lat":@"12.975578333333333",@"lng":@"77.71165500000001",@"app_type":@"1"};
        NSLog(@"%@",dict);
        [delObj PostWebServer:dict type:@"http://aiv2.ibbtrade.com/login"];
//        accessToken = Gzzi4FFEQDkd7rx16GbKgpjE0IhdZyJxREwy8PVm;

    }
}
-(void)getMatchingResponse:(NSNotification *)dict{
   
    [delObj hideView];
    NSDictionary *dictValue=[dict userInfo];
   if([[dictValue objectForKey:@"status"] isEqualToString:@"true"])
   {
       DetailViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"DashboardView"];
       [dvc setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
       [self presentViewController:dvc animated:YES completion:nil];

   }
    else
    {
        NSLog(@"NO");

    }
//    CategoryListArray=(NSMutableArray *)[NSArray arrayWithArray:[dictValue valueForKey:@"Response"]];
//    NSLog(@"%@",CategoryListArray);
   
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


DetailView:

#import <UIKit/UIKit.h>

@interface DetailViewController : UIViewController
{
    NSMutableArray *yearArray;
}
@end



#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    yearArray = [[NSMutableArray alloc] init];
   
    for (int i = 1990; i < 2018; i++)
    {
//        NSString *string = i;
        NSLog(@"%d",i);
        [yearArray addObject:[NSString stringWithFormat:@"%d",i]];
        // Do stuff...
    }
}


Thursday, September 22, 2016

NSUserDefault in swift, Xcode 8 and iOS 10 & Objective C

NSUserDefaults with Xcode 8 and iOS 10


let defaults = UserDefaults.standard

Swift Saving a data to NSUserDefaults before Xcode 8

NSUserDefaults.standardUserDefaults().setObject(your parameter, forKey: "Key")
NSUserDefaults.standardUserDefaults().setObject(your parameter1, forKey: "Key1")

//synchronizing

NSUserDefaults.standardUserDefaults().synchronize()

// Assign the NSUserDefault value to particular variable.

let parameter1 = NSUserDefaults.standardUserDefaults().objectForKey("Key")! as! String

Objective C:


[[NSUserDefaults standardUserDefaults] setObject:"Your object" forKey:@"Key"];
[[NSUserDefaults standardUserDefaults] setObject:"Your Object" forKey:@"Key"];
[[NSUserDefaults standardUserDefaults] synchronize]


// Assign the NSUserDefault value to particular variable.

str1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"entity_id"];
str2 = [[NSUserDefaults standardUserDefaults] objectForKey:@"entity_String"]

How to create the bridge header file in swift


Flow :

  1. Add a new file to Xcode (File > New > File), then select “Source” and click “Header File“.
  2. Name your file “YourProjectName-Bridging-Header.h”.  
  3. Create the file.
  4. Navigate to your project build settings and find the “Swift Compiler – Code Generation” section.  You may find it faster to type in “Swift Compiler” into the search box to narrow down the results.  Note: If you don’t have a “Swift Compiler – Code Generation” section, this means you probably don’t have any Swift classes added to your project yet.  Add a Swift file, then try again.
  5. Next to “Objective-C Bridging Header” you will need to add the name/path of your header file.  If your file resides in your project’s root folder simply put the name of the header file there.  
  6. Open up your newly created bridging header and import your Objective-C classes using #importstatements.  Any class listed in this file will be able to be accessed from your swift classes.



NSDateFormatter in Swift


        let eventdate = "Picker date or get the date from server"
        let YearFormat = NSDateFormatter()
        YearFormat.dateFormat = "yyyy-MM-dd"
        let hryDate = YearFormat.dateFromString(eventdate!.stringByReplacingOccurrencesOfString          ("T00:00:00", withString: "").stringByReplacingOccurrencesOfString("-", withString: "/"))
        let monthFormat = NSDateFormatter()
        monthFormat.dateFormat = "MM.dd.YY" //"MMM.dd.yy" (OR) "dd.MMM.yyyy"

        cell.expenseDateLabel.text = monthFormat.stringFromDate(hryDate!) 

                                      (or)

        let dateString = dateFormatter12.stringFromDate(hryDate!)

Singleton Class in Swift (Global shared data)



First we have to create the empty file.

Xcode -> New -> File -> Others -> Empty file


//  GlobalData.swift

class GlobalData {
    
    var defaultLocationID : String = "0"
    var userEmailsave :String = ""
    var userLocationAdress : String = ""
    var userLocationArray : NSMutableArray!
    var userLocationSelected : String = ""
    var tokenAPI : NSString = ""
    var default_location_name : String = ""
    var userName : String = ""
    
    // Here is how you would get to it without there being a global collision of variables.
    // , or in other words, it is a globally accessable parameter that is specific to the
    // class.
    class var sharedManager: GlobalData {
        struct Static {
            static let instance = GlobalData()
        }
        return Static.instance
    }

}


//   HomeViewController.Swift

 GlobalData.sharedManager.userName = "Facebook Username or google username"

we can access the global data like this.

HTTPS Webservice call in swift & serverTrust code

 Server Trust Code:

 func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
{
   if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
   {
       let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
       completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential);
   }
   else
   {
       completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
   }

}

In Plist we can add below code:

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSExceptionDomains</key>
        <dict>
            <key>"Your url"</key>
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSExceptionRequiresForwardSecrecy</key>
                <true/>
                <key>NSExceptionMinimumTLSVersion</key>
                <string>TLSv1.2</string>
                <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
                <false/>
                <key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
                <true/>
                <key>NSThirdPartyExceptionMinimumTLSVersion</key>
                <string>TLSv1.2</string>
                <key>NSRequiresCertificateTransparency</key>
                <false/>
            </dict>
        </dict>
    </dict>



let parameters = ["UserEmail":userMailID, "DeviceUDID": stringUDID] as Dictionary<StringString>
let url = NSURL (string: "Your URL"//change the url
let request = NSMutableURLRequest(URL: url!)
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue())
                
request.HTTPMethod = "POST" //set http method as POST
request.HTTPBody = tryNSJSONSerialization.dataWithJSONObject(parameters, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//                request.timeoutInterval = 100
let task = session.dataTaskWithRequest(request)
{
    data, response, error in
    guard data != nil else
    {
      // Error response
    }                 
        //RESPONSE HEADER RESULT
                    
        let httpsResponse = response asNSHTTPURLResponse
        let str = httpsResponse!.allHeaderFields as NSDictionary
        let tokenStr = str["TokenAPI"asString
         GlobalData.sharedManager.tokenAPI = tokenStr
         let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
         self.json = try NSJSONSerialization.JSONObjectWithData      ((jsonStr?.dataUsingEncoding(NSUTF8StringEncoding)!)!, options: .AllowFragments)
      Print(self.json)
}
   task.resume()