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

Calling action & Mail action in tableview in swift




@IBAction func locationphoneTapped(sender: UITapGestureRecognizer)
    {
        let tapLocation = sender.locationInView(self.tableView)
        //using the tapLocation, we retrieve the corresponding indexPath
        let indexPath = self.tableView.indexPathForRowAtPoint(tapLocation)
        let s3 = self.resultArray[(indexPath?.section)!] .valueForKey("PhoneNumber") as? String
        let phoneNumber: String = "telprompt://".stringByAppendingString(s3!)
        UIApplication.sharedApplication().openURL(NSURL(string: phoneNumber)!)
    }
    
    @IBAction func locationMailAction(sender: UITapGestureRecognizer)
    {
        let email = self.locationArray[0].valueForKey("EmailID") as? String
        let phoneNumber: String = "mailto://".stringByAppendingString(email!)
        let url = NSURL(string: phoneNumber)
        UIApplication.sharedApplication().openURL(url!)

    }




NSURLSession Web service call in Swift



let parameters = ["UserEmail":userMailID, "DeviceUDID": stringUDID] as Dictionary<String, String>
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 = try! NSJSONSerialization.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 as? NSHTTPURLResponse
        let str = httpsResponse!.allHeaderFields as NSDictionary
        let tokenStr = str["TokenAPI"] as! String
         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()

UIImagePicker (Photo Library, Camera) in swift

Variable declaration:

    let imagePicker = UIImagePickerController()
    @IBOutlet weak var imageButton: UIButton!
    var image_data: NSData?

Methods:

 @IBAction func imageButtonDidPress(sender: AnyObject)
    {
        //show the action sheet (i.e. the little pop-up box from the bottom that allows you to choose whether you want to pick a photo from the photo library or from your camera
        let optionMenu = UIAlertController(title: nil, message: "Get Photo", preferredStyle: UIAlertControllerStyle.ActionSheet)
        
        let photoLibraryOption = UIAlertAction(title: "Photo Library", style: UIAlertActionStyle.Default, handler: { (alert: UIAlertAction!) -> Void in
            //shows the photo library
            self.imagePicker.allowsEditing = true
            self.imagePicker.sourceType = .PhotoLibrary
            self.imagePicker.modalPresentationStyle = .Popover
            self.presentViewController(self.imagePicker, animated: true, completion: nil)
        })
        let cameraOption = UIAlertAction(title: "Take Photo", style: UIAlertActionStyle.Default, handler: { (alert: UIAlertAction!) -> Void in
            //shows the camera
            self.imagePicker.allowsEditing = true
            self.imagePicker.sourceType = .Camera
            self.imagePicker.modalPresentationStyle = .Popover
            self.presentViewController(self.imagePicker, animated: true, completion: nil)
            
        })
        let cancelOption = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: {
            (alert: UIAlertAction!) -> Void in
        })
        
        //Adding the actions to the action sheet. Camera will only show up as an option if the camera is available in the first place.
        optionMenu.addAction(photoLibraryOption)
        optionMenu.addAction(cancelOption)
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) == true {
            optionMenu.addAction(cameraOption)} else {
        }
        self.presentViewController(optionMenu, animated: true, completion: nil)
    }
    
    
    //The UIImagePickerController is a view controller that gets presented modally. When we select or cancel the picker, it runs the delegate, where we handle the case and dismiss the modal.
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        self.imageButton.setBackgroundImage(image, forState: UIControlState.Normal)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        //handle media here i.e. do stuff with photo
        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        self.imageButton.setBackgroundImage(chosenImage, forState: UIControlState.Normal)
        
        dismissViewControllerAnimated(true, completion: nil)
    }

    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        //what happens when you cancel
        //which, in our case, is just to get rid of the photo picker which pops up
        dismissViewControllerAnimated(true, completion: nil)

    }