Git Product home page Git Product logo

networkmanager's Introduction

Write Your Own API Manager for iOS

We are going to write API manager for iOS which uses URLSession. URLSession is suitable for handing HTTP/HTTPS requests. I used to depend on third-party libraries like “Alamofire” or “AFNetworking”. We are going to create the API Manager class using NSURLSession. Which is fairly simple and easy to implement.

URLSessionTask

URLSessionTask: This method determines the type of task. There are mainly 3 types of tasks.

datatask: Data task requests a resource and server returns objects as NSData.

downloadtask: Download task, download a resource directly to file in the disk.

uploadtask: Use this task to upload a file from disk to a web service with HTTP POST or PUT method.

URLSessionConfiguration

A configuration object that defines behavior and policies for a URL session.

There are 3 types of session configurations are available.

  • default: Creates a default configuration object that uses the disk-persisted global cache, credential, and cookie storage objects.
  • ephemeral: Similar to the default configuration, except that all session-related data is stored in memory. Think of this as a “private” session.
  • background: Lets the session perform upload or download tasks in the background. Transfers continue even when the app itself is suspended or terminated by the system.

URLRequest

URLRequest represents information about the request.

URLRequest consists of an HTTP method (GET, POST, etc) and the HTTP headers.

Below you can see network manager class which can handle HTTP requests

    import Foundation
    
    enum HttpMethod:String{
        case get = "get"
        case post = "post"
    }
    
    let BaseURL : String = "http://dummy.restapiexample.com/api/v1/"
    
    class NetworkManager {
        
        static let shared = NetworkManager()
        
        func dataTask(serviceURL:String,httpMethod:HttpMethod,parameters:[String:String]?,completion:@escaping (AnyObject?, Error?) -> Void) -> Void {
           
            requestResource(serviceURL: serviceURL, httpMethod: httpMethod, parameters: parameters, completion: completion)
        }
        
        private func requestResource(serviceURL:String,httpMethod:HttpMethod,parameters:[String:String]?,completion:@escaping (AnyObject?, Error?) -> Void) -> Void {
            
            var request = URLRequest(url: URL(string:"\(BaseURL)\(serviceURL)")!)
           
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.httpMethod = httpMethod.rawValue
            
            if (parameters != nil) {
                request.httpBody = try? JSONSerialization.data(withJSONObject: parameters!, options: .prettyPrinted)
            }
            
            let sessionTask = URLSession(configuration: .default).dataTask(with: request) { (data, response, error) in
                
                if (data != nil){
                    let result = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                    completion (result as AnyObject, nil)
                }
                    
                if (error != nil) {
                    completion (nil,error!)
                }
            }
            sessionTask.resume()
        }
    }

Invoke HTTP Get

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NetworkManager.shared.dataTask(serviceURL: "employees", httpMethod: .get, parameters: nil) { (response, error) in
            if response != nil {
                print(response)
            }
            if error != nil {
                print("Error Occoured")
            }
        } 
    }
}

HTTP POST

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        NetworkManager.shared.dataTask(serviceURL: "create", httpMethod: .post, parameters: ["name":"rinto","salary":"456","age":"30"]) { (response, error) in
            if response != nil {
                print(response)
            }
            if error != nil {
                print("Error Occoured")
            }
        }
    }
}

networkmanager's People

Contributors

rintoandrews90 avatar

Stargazers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.