swift Api call demo

Ceate one new class give that name is like this and copy that code in side that file

import UIKit

class APIConnection: NSObject,URLSessionDelegate {

    class var sharedInstance: APIConnection {
        struct Static {
            static var onceToken: Int = 0
            static var instance = APIConnection()
        }
        return Static.instance
    }
 
    func PostResponseFrom(strUrl:String ,Parameter:NSMutableDictionary, completionHandler:@escaping (_ result:Any, _ status:Bool, _ statusCode:CLong)->Void ) -> ()
    {
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
     
        let postUrl = URL(string: strUrl)
     
        let Request = NSMutableURLRequest(url: postUrl!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 60)
        Request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        Request.addValue("application/json", forHTTPHeaderField: "Accept")
     
        do {
            let data = try JSONSerialization.data(withJSONObject: Parameter, options: .prettyPrinted)
            Request.httpBody=data
        } catch
        {
            print(error)
        }
        Request.httpMethod="POST"
     
        let task:URLSessionDataTask = session.dataTask(with: Request as URLRequest){
            data,response,error in
         
            if error != nil
            {
                print(error?.localizedDescription as Any)
                let httpResponse : HTTPURLResponse = response as! HTTPURLResponse
                completionHandler(error?.localizedDescription as Any,false,httpResponse.statusCode)
                return
            }
            do
            {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                if let parseJSON = json
                {
                    print(parseJSON)
                    let httpResponse : HTTPURLResponse = response as! HTTPURLResponse
                    completionHandler(parseJSON,(error ==  nil),httpResponse.statusCode)
                }
            }
            catch let error as NSError
            {
                let httpResponse : HTTPURLResponse = response as! HTTPURLResponse
                completionHandler(error.localizedDescription as Any,false,httpResponse.statusCode)
                print(error)
            }
        }
        task.resume()
    } 
}

Than call that file in to you swift class

func getdata()
    {     
        let para = NSMutableDictionary()
     
        para.setObject("123", forKey: "userid" as NSCopying)

        APIConnection.sharedInstance.PostResponseFrom(strUrl: "your URL", Parameter: para) { (Response, Status, Statuscode) in
            print(Response)
            print(Status)
            print(Statuscode)
       
                if let responsestate = (Response as AnyObject).value(forKey: "responseState") as? NSDictionary
                {
                     if let sts = (responsestate).value(forKey: "status") as? Int
                     {
                        if sts == 0
                        {
                            self.Responselabel.text! = ((responsestate).value(forKey: "message") as? String)!
                        }
                        else
                        {
                         
                        }
                    }
            }
        }
     
    }

Comments

Popular posts from this blog

Windows Keys

how to send invite and give a access of selected application on App Store

how to display popover in TableView cell in swift