Skip to main content

Common API Request Class

//
//  Connection.swift
//  Norwood
//
//  Created by Praveen Reddy on 10/01/19.
//  Copyright © 2019 Apple. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON

class Connection
{
    
    func requestPOST(_ url: String, params : Parameters?, headers : HTTPHeaders?, success:@escaping (Data) -> Void, failure:@escaping (Error) -> Void)
    {
        
        print("URL = ",url)
        print("Parameter = ",params!)
        
        
//        if Connectivity.isConnectedToInternet()
//        {
            if headers == nil
            {
                Alamofire.request(url, method: .post, parameters: params!, encoding: JSONEncoding.default, headers: nil).responseJSON
                    {
                        (responseObject) -> Void in
                        
                        print("Response = ",responseObject)
                        
                        switch responseObject.result
                        {
                        case .success:
                            if let data = responseObject.data
                            {
                                success(data)
                            }
                        case .failure(let error):
                            failure(error)
                        }
                        
                }
            }
            else
            {
                
                print("Headers = ",headers!)
                
                Alamofire.request(url, method: .post, parameters: params!, encoding: JSONEncoding.default, headers: headers!).responseJSON
                    {
                        (responseObject) -> Void in
                        
                        print("Response = ",responseObject)
                        
                        switch responseObject.result
                        {
                        case .success:
                            if let data = responseObject.data
                            {
                                success(data)
                            }
                        case .failure(let error):
                            failure(error)
                        }
                        
                }
            }
            
//        }
//        else
//        {
//            let err = NSError(domain: "Check Internet Connection", code: 401, userInfo: nil)
//            failure(err)
//
//        }
    }
    
    
    func requestGET(_ url: String, params : Parameters?,headers : [String : String]?, success:@escaping (Data) -> Void, failure:@escaping (Error) -> Void)
    {
        
        do
        {
            Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON
                {
                    (response) in
                    switch response.result
                    {
                    case .success:
                        if let data = response.data
                        {
                            success(data)
                        }
                    case .failure(let error):
                        failure(error)
                    }
            }
            
            
            
        }
        catch let JSONError as NSError
        {
            failure(JSONError)
        }
        
    }
    

    
    
    func requestMultiPartDataPOST(_ url: String, parameters : [String : Any], imageData: Data?,headers : HTTPHeaders?, success:@escaping (Data) -> Void, failure:@escaping (Error) -> Void)
    {
        
        print("URL = ",url)
        print("Parameter = ",parameters)
        
        if Connectivity.isConnectedToInternet()
        {
            
            let headers: HTTPHeaders = [
                "Content-type""multipart/form-data"
            ]
            
            Alamofire.upload(multipartFormData: { (multipartFormData) in
                for (key, value) in parameters {
                    multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
                }
                
                if let data = imageData{
                    multipartFormData.append(data, withName: "file", fileName: "image.png", mimeType: "image/png")
                }
                
            }, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
                switch result{
                case .success(let upload, __):
                    upload.responseJSON { response in
                        print("Succesfully uploaded")
                        if let result = response.data{
                            
                            success(result)
                        }
                    }
                case .failure(let error):
                    print("Error in upload: \(error.localizedDescription)")
                    failure(error)
                }
            }
            
        }
        else
        {
            
            //            let err = NSError(domain: "Check Internet Connection".localized(), code: nil, userInfo: nil)
            //            let error = NSError(domain: "", code: 4, userInfo: "Check Internet Connection")
            ////
            //            failure(error)
        }
    }
    
    
    // requestpost with  anyobject data format
    
    func requestPOSTDict(_ url: String, params : Parameters?, headers : [String : String]?, success:@escaping (JSON) -> Void, failure:@escaping (Error) -> Void){
        
        Alamofire.request(url, method: .post, parameters: params!, encoding: JSONEncoding.default, headers: headers!).responseJSON
            {
                (responseObject) -> Void in
                
                print("Response = ",responseObject)
                
                if responseObject.result.isSuccess {
                    let resJson = JSON(responseObject.result.value!)
                    success(resJson)
                }
                if responseObject.result.isFailure {
                    let error : Error = responseObject.result.error!
                    failure(error)
                }
                
        }

    }

}



Comments

Popular posts from this blog

API Calling Example

import  Foundation import  Alamofire class  HomeViewModel {           let  sharedInstance = Connection()      var  reloadHandler:  DataHandler  = { }      typealias  DataHandler = () ->  Void      init () { }           //--------------------------------------------------      // MarK : fetchInitialSetup    API Integration      //--------------------------------------------------      func  fetchInitialSetup(success: @escaping  ( GetLocationAndDevicesModel ) ->  Void , failure: @escaping  ( Error ) ->  Void )      {          let  URL = AddDeviceList().getUrlString(url: .CREATE_API)                   let  headers :...

TAGS in swift

github link : https://github.com/ElaWorkshop/TagListView Simple and highly customizable iOS tag list view, in Swift. Supports Storyboard, Auto Layout, and @IBDesignable. Usage The most convenient way is to use Storyboard. Drag a view to Storyboard and set Class to  TagListView  (if you use CocoaPods, also set Module to  TagListView ). Then you can play with the attributes in the right pane, and see the preview in real time thanks to  @IBDesignable . You can add tag to the tag list view, or set custom font and alignment through code: tagListView. textFont = UIFont. systemFontOfSize ( 24 ) tagListView. alignment = . Center // possible values are .Left, .Center, and .Right tagListView. addTag ( " TagListView " ) tagListView. addTags ([ " Add " , " two " , " tags " ]) tagListView. insertTag ( " This should be the second tag " , at : 1 ) tagListView. setTitle ( " New Title " , at : 6 ) // to repla...