Wednesday, 22 June 2016

Simple GET & POST Using Swift

Simple GET & POST Using Swift ( HTTP )



Json GET :-


  override func viewDidLoad() {
        super.viewDidLoad()
        
        
        //------------------------------------------- First Method of Json GET
        


let school = NSMutableArray()
        
        let miadata = NSData(contentsOfURL: NSURL(string: "http:...../api/getallschools")!)
        
        do{
            let MyData = try NSJSONSerialization.JSONObjectWithData(miadata!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
            
            print(".........\(MyData)")
            
            let array = MyData?.valueForKey("data")?.valueForKey("school_title")
            
            school.addObjectsFromArray((array)! as! [AnyObject])
            
            print("School name: \(school)")
            
            for (var i = 0; i < school.count; i += 1)
            {
                print("Index: \(school[i])")
            }
            
            
            
        }
        catch let error as NSError
        {
            
            // error.description
            print(error.description)
        }

        


        //------------------------------------------- Second Method of Json GET
        
        /*
        let requestURL: NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
        let data = NSData(contentsOfURL: requestURL)
        
        do{
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
            
            if let stations = json["stations"] as? [[String: AnyObject]]
            {
                for station in stations
                {
                    if let name = station["stationName"] as? String
                    {
                        if let year = station["buildYear"] as? String
                        {
                            print(name,year)
                        }
                    }
                }
            }
        }
        catch let error as NSError
        {
            print(error.localizedDescription)
        }
        */
                //------------------------------------------- Third Method of Json GET

                /*
        let requestURL: NSURL = NSURL(string: "http://www.learnswiftonline.com/Samples/subway.json")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in
            
            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode
            
            if (statusCode == 200) {
                
                do{
                    
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
                    
                    if let stations = json["stations"] as? [[String: AnyObject]] {
                        
                        for station in stations {
                            
                            if let name = station["stationName"] as? String {
                                
                                if let year = station["buildYear"] as? String {
                                    print(name,year)
                                }
                                
                            }
                        }
                        
                    }
                    
                }catch {
                    print("Error with Json: \(error)")
                }
                
            }
            
            /*
            if (statusCode == 200) {
                print("Everyone is fine, file downloaded successfully.")
            }*/
        }
        
        task.resume()*/
       
        
    }








Json POST :-




  override func viewDidLoad() {
        super.viewDidLoad()

            //------------------------------------------- json post
        
        let request = NSMutableURLRequest(URL: NSURL(string: "YOUR_URL")!)
        request.HTTPMethod = "POST"
        let postString = "user_id=385&org_id=45"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
            guard error == nil && data != nil else {                                                          // check for fundamental networking error
                print("error=\(error)")
                return
            }
            
            if let httpStatus = response asNSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }
            
            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString = \(responseString)")
        }
        task.resume()

}






No comments:

Post a Comment