Saturday, 29 April 2017

Json Get & POST using Swift 3.0

Json Get & POST using Swift 3.0



Add This In info.plist :-

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>


Get Data Using Json File  :-


Add .json File in Bundle Like This :



{
    "MONDAY": [
               {
               "TITLE": "TEST DRIVEN DEVELOPMENT",
               "SPEAKER": "JASON SHAPIRO",
               "TIME": "9:00 AM",
               "ROOM": "MATISSE",
               "DETAILS": "EXPLORE THE TOPICS AND TOOLS RELATED TO TEST DRIVEN DEVELOPMENT."
               },
               {
               "TITLE": "JAVA TOOLS",
               "SPEAKER": "JIM WHITE",
               "TIME": "9:00 AM",
               "ROOM": "ROTHKO",
               "DETAILS": "DISCUSS THE LATEST SET OF TOOLS USED TO HELP EASE SOFTWARE DEVELOPMENT."
               }
               ],
    "TUESDAY": [
                {
                "TITLE": "MONGODB",
                "SPEAKER": "DAVINMICKELSON",
                "TIME": "1: 00PM",
                "ROOM": "PICASSO",
                "DETAILS": "LEARNABOUT\"NOSQL\"DATABASES."
                },
                {
                "TITLE": "DEBUGGINGWITHXCODE",
                "SPEAKER": "JASONSHAPIRO",
                "TIME": "1: 00PM",
                "ROOM": "VANGOGH",
                "DETAILS": "EXPLOREDIFFERENTPATTERNSFORDEBUGGINGYOURIOSAPPS."
                }
                ],
    "WEDNESDAY": [
                  {
                  "TITLE": "SCRUM MASTER",
                  "SPEAKER": "DAVIN MICKELSON",
                  "TIME": "1:00 PM",
                  "ROOM": "MATISSE",
                  "DETAILS": "LEARN THE ROLES AND RESPONSIBILITIES OF A SCRUM MASTER"
                  },
                  {
                  "TITLE": "DESIGN PATTERNS",
                  "SPEAKER": "JIM WHITE",
                  "TIME": "1:00 PM",
                  "ROOM": "ROTHKO",
                  "DETAILS": "APPLY BEST PRACTICES AND SOUND ARCHITECTURES TO SOFTWARE DESIGN."
                  }
                  ]
}



Coding Part : -





import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate
{
    
    var arrDict :NSMutableArray=[]
    
    @IBOutlet weak var tvJSON: UITableView!
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
             
        //-------------- Get Method
        
       
            jsonParsingFromFile()
   
    }
      
    func jsonParsingFromFile()
    {
        let path: NSString = Bundle.main.path(forResource: "days", ofType: "json")! as NSString
        let data : Data = try! Data(contentsOf: URL(fileURLWithPath: path as String), options: NSData.ReadingOptions.dataReadingMapped)
        
        self.startParsing(data)
    }
    
    func startParsing(_ data :Data)
    {
        let dict: NSDictionary!=(try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary
        
        print(dict)
        
        for i in 0  ..< (dict.value(forKey: "MONDAY") as! NSArray).count 
        {
            arrDict.add((dict.value(forKey: "MONDAY") as! NSArray) .object(at: i))
        }
        for i in 0  ..< (dict.value(forKey: "TUESDAY") as! NSArray).count 
        {
            arrDict.add((dict.value(forKey: "TUESDAY") as! NSArray) .object(at: i))
        }
        for i in 0  ..< (dict.value(forKey: "WEDNESDAY") as! NSArray).count 
        {
            arrDict.add((dict.value(forKey: "WEDNESDAY") as! NSArray) .object(at: i))
        }
        tvJSON .reloadData()
    }
    
    func numberOfSections(in tableView: UITableView) -> Int
    {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return arrDict.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell : TableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Cell") as! TableViewCell
        let strTitle : NSString=(arrDict[indexPath.row] as AnyObject).value(forKey: "TITLE") as! NSString
        let strDescription : NSString=(arrDict[indexPath.row] as AnyObject).value(forKey: "DETAILS") as! NSString
        cell.lblTitle.text=strTitle as String
        cell.lbDetails.text=strDescription as String
        return cell as TableViewCell
    }
}





Get Method Using URL :- 




@IBOutlet weak var tvJSON: UITableView!
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        
        //-------------- Get Method
       
            jsonParsingFromURL()

    }
       
    func jsonParsingFromURL () {
        let url = URL(string: "https://api.github.com/users/mralexgray")
        let request = URLRequest(url: url!)
        
        NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {(response, data, error) in
            self.startParsing(data!)
        }
    }
    
    
    func startParsing(_ data :Data)
    {
        let dict: NSDictionary!=(try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)) as! NSDictionary
        
        print(dict)

   }




Json POST Method :-



Method 1 :-


 //----------------------------------   post Method
        
        //------------------------ Method 1
        
        
        let json: [String: Any] = ["title": "ABC",
                                   "dict": ["1":"First", "2":"Second"]]
        
        let jsonData = try? JSONSerialization.data(withJSONObject: json)
        
        // create post request
        let url = URL(string: "http://httpbin.org/post")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        
        // insert json data to the request
        request.httpBody = jsonData
        
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print(error?.localizedDescription ?? "No data")
                return
            }
            let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
            if let responseJSON = responseJSON as? [String: Any] {
                print(responseJSON)
            }
        }
        
        task.resume()
        
        
Method 2 :-


        //------------------------ Method 2
        
        
        let json: [String: Any] = ["title": "ABC",
                                   "dict": ["1":"First", "2":"Second"]]
        
        
        
        do {
            
            let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
            
            // create post request
            let url = NSURL(string: "http://httpbin.org/post")!
            let request = NSMutableURLRequest(url: url as URL)
            request.httpMethod = "POST"
            
            // insert json data to the request
            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.httpBody = jsonData
            
            
            let task = URLSession.shared.dataTask(with: request as URLRequest){ data, response, error in
                if error != nil{
                    print("Error -> \(error)")
                    return
                }
                
                do {
                    let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
                    
                    print("Result -> \(result)")
                    
                } catch {
                    print("Error -> \(error)")
                }
            }
            
            task.resume()

        } catch {
            print(error)
        }
        
        

Method 3 :-

        
        //------------------------ Method 3
        
        
        var request = URLRequest(url: URL(string: "http://httpbin.org/post")!)
        request.httpMethod = "POST"
        let postString = "title=ABC&dict=1"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {                                                 // check for fundamental networking error
                print("error=\(error)")
                return
            }
            
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }
            
            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")
        }
        task.resume()












Wednesday, 26 April 2017

UITextView with clickable links to actions

UITextView with clickable links to actions



Want to make this:










Set IBoutlet of UITextview :



@property(weak, nonatomic) IBOutlet UITextView *agreeTextContainerView ;





- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    
    [self buildAgreeTextViewFromString:NSLocalizedString(@"I agree to the #<ts>terms of service# and #<pp>privacy policy#",
                                                         @"PLEASE NOTE: please translate \"terms of service\" and \"privacy policy\" as well, and leave the #<ts># and #<pp># around your translations just as in the English version of this message.")];

}



- (void)buildAgreeTextViewFromString:(NSString *)localizedString
{
    // 1. Split the localized string on the # sign:
    NSArray *localizedStringPieces = [localizedString componentsSeparatedByString:@"#"];
    
    // 2. Loop through all the pieces:
    NSUInteger msgChunkCount = localizedStringPieces ? localizedStringPieces.count : 0;
    CGPoint wordLocation = CGPointMake(0.0, 0.0);
    for (NSUInteger i = 0; i < msgChunkCount; i++)
    {
        NSString *chunk = [localizedStringPieces objectAtIndex:i];
        if ([chunk isEqualToString:@""])
        {
            continue;     // skip this loop if the chunk is empty
        }
        
        // 3. Determine what type of word this is:
        BOOL isTermsOfServiceLink = [chunk hasPrefix:@"<ts>"];
        BOOL isPrivacyPolicyLink  = [chunk hasPrefix:@"<pp>"];
        BOOL isLink = (BOOL)(isTermsOfServiceLink || isPrivacyPolicyLink);
        
        // 4. Create label, styling dependent on whether it's a link:
        UILabel *label = [[UILabel alloc] init];
        label.font = [UIFont systemFontOfSize:15.0f];
        label.text = chunk;
        label.userInteractionEnabled = isLink;
        
        if (isLink)
        {
            label.textColor = [UIColor colorWithRed:110/255.0f green:181/255.0f blue:229/255.0f alpha:1.0];
            label.highlightedTextColor = [UIColor yellowColor];
            
            // 5. Set tap gesture for this clickable text:
            SEL selectorAction = isTermsOfServiceLink ? @selector(tapOnTermsOfServiceLink:) : @selector(tapOnPrivacyPolicyLink:);
            UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                         action:selectorAction];
            [label addGestureRecognizer:tapGesture];
            
            // Trim the markup characters from the label:
            if (isTermsOfServiceLink)
                label.text = [label.text stringByReplacingOccurrencesOfString:@"<ts>" withString:@""];
            if (isPrivacyPolicyLink)
                label.text = [label.text stringByReplacingOccurrencesOfString:@"<pp>" withString:@""];
        }
        else
        {
            label.textColor = [UIColor blackColor];
        }
        
        // 6. Lay out the labels so it forms a complete sentence again:
        
        // If this word doesn't fit at end of this line, then move it to the next
        // line and make sure any leading spaces are stripped off so it aligns nicely:
        
        [label sizeToFit];
        
        if (self.agreeTextContainerView.frame.size.width < wordLocation.x + label.bounds.size.width)
        {
            wordLocation.x = 0.0;                       // move this word all the way to the left...
            wordLocation.y += label.frame.size.height// ...on the next line
            
            // And trim of any leading white space:
            NSRange startingWhiteSpaceRange = [label.text rangeOfString:@"^\\s*"
                                                                options:NSRegularExpressionSearch];
            if (startingWhiteSpaceRange.location == 0)
            {
                label.text = [label.text stringByReplacingCharactersInRange:startingWhiteSpaceRange
                                                                 withString:@""];
                [label sizeToFit];
            }
        }
        
        // Set the location for this label:
        label.frame = CGRectMake(wordLocation.x,
                                 wordLocation.y,
                                 label.frame.size.width,
                                 label.frame.size.height);
        // Show this label:
        [self.agreeTextContainerView addSubview:label];
        
        // Update the horizontal position for the next word:
        wordLocation.x += label.frame.size.width;
    }
}


- (void)tapOnTermsOfServiceLink:(UITapGestureRecognizer *)tapGesture
{
    if (tapGesture.state == UIGestureRecognizerStateEnded)
    {
        NSLog(@"User tapped on the Terms of Service link");
    }
}


- (void)tapOnPrivacyPolicyLink:(UITapGestureRecognizer *)tapGesture
{
    if (tapGesture.state == UIGestureRecognizerStateEnded)
    {
        NSLog(@"User tapped on the Privacy Policy link");
    }
}