[Swift 3] HTTP Request 사용하기, 클래스 소스코드 및 사용법

by digipine posted Nov 02, 2017
?

Shortcut

PrevPrev Article

NextNext Article

ESCClose

Larger Font Smaller Font Up Down Go comment Print

Swift 3.0 으로 변하면서 NS라는 Prefix 명들이 모두 사라져서 깔끔해  느낌인데 여러가지로 API 바뀌어서 매우 혼동이 됩니다.

그래서 특히 많이 사용하는 HTTP request  정리해 보았습니다.

 

import Foundation

 

class Request {

    let session: URLSession = URLSession.shared

    

    // GET METHOD

    func get(url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {

        var request: URLRequest = URLRequest(url: url)

        

        request.httpMethod = "GET"

        request.addValue("application/json", forHTTPHeaderField: "Accept")

        session.dataTask(with: request, completionHandler: completionHandler).resume()

    }

    

    // POST METHOD

    func post(url: URL, body: NSMutableDictionary, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Voidthrows {

        var request: URLRequest = URLRequest(url: url)

        

        request.httpMethod = "POST"

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.httpBody = try JSONSerialization.data(withJSONObject: body, options: JSONSerialization.WritingOptions.prettyPrinted)

        

        session.dataTask(with: request, completionHandler: completionHandler).resume()

    }

    

    // PUT METHOD

    func put(url: URL, body: NSMutableDictionary, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Voidthrows {

        var request: URLRequest = URLRequest(url: url)

        

        request.httpMethod = "PUT"

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.httpBody = try JSONSerialization.data(withJSONObject: body, options: JSONSerialization.WritingOptions.prettyPrinted)

        session.dataTask(with: request, completionHandler: completionHandler).resume()

    }

    

    // PATCH METHOD

    func patch(url: URL, body: NSMutableDictionary, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Voidthrows {

        var request: URLRequest = URLRequest(url: url)

        

        request.httpMethod = "PATCH"

        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.httpBody = try JSONSerialization.data(withJSONObject: body, options: JSONSerialization.WritingOptions.prettyPrinted)

        session.dataTask(with: request, completionHandler: completionHandler).resume()

    }

    

    // DELETE METHOD

    func delete(url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) {

        var request: URLRequest = URLRequest(url: url)

        

        request.httpMethod = "DELETE"

        request.addValue("application/json", forHTTPHeaderField: "Accept")

        session.dataTask(with: request, completionHandler: completionHandler).resume()

    }

 

}

 


 

 

사용예

 

let request: Request = Request()

 

let url: URL = URL(string: "https://api.example.com/path/to/resource")!

let body: NSMutableDictionary = NSMutableDictionary()

body.setValue("value", forKey: "key")

 

try request.post(url: url, body: body, completionHandler: { data, response, error in

    // code

 

}) 

 
TAG •

Articles

1 2 3