Wednesday, 21 February 2018

POST Method and GET Method - Call API - Swift


POST Method and GET Method - Call API - Swift
func callEmailApi(uploadUrl:String, fileName:String)
{
    let params = "frm_test1=\(test1_val)& frm_test2=\(test2_val)& frm_test3=\(test3_val)"
    print("param",params)
    _ = postMethod(urlStr: "http://googl.dad/api/api_3/smail", params: params, completionHandler: { (jsonData, error) in
        if let jsonData =  jsonData{
            let succed = jsonData["success"] as? Bool
            let error_message = jsonData["err_msg"] as? String
            let error_modes = jsonData["err_mode"] as? Int
            if(succed == true)
            {
                print("success",error_message)
            }
            else
            {
                print("failed",error_message)
            }
        }
        else
        {
            //  handle error
            print("API NOT WORK")
         
        }
    })
}

func postMethod(urlStr: String, params: String, completionHandler: @escaping ([String:AnyObject]?, NSError?) -> Void ) -> URLSessionTask
{
    var request = URLRequest(url: URL(string: urlStr)!)
    request.httpMethod = "POST"
    let postString = params
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if error != nil{
            completionHandler(nil, error as NSError?)
            return
        }
        do {
            let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
            completionHandler(result, nil)
            //   print("result",result)
        } catch {
            completionHandler(nil, error as NSError?)
            print("error",error.localizedDescription)
        }
    }
    task.resume()
    return task
}

func getMethod(urlStr: String, completionHandler: @escaping ([String:AnyObject]?, NSError?) -> Void ) -> URLSessionTask
{
    var request = URLRequest(url: URL(string: urlStr)!)
    request.httpMethod = "GET"
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        if error != nil{
            completionHandler(nil, error as NSError?)
            return
        }
     
        do {
            let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]
            completionHandler(result, nil)
        } catch {
            completionHandler(nil, error as NSError?)
        }    }
    task.resume()
    return task
}

No comments: