logo

English

이곳의 프로그래밍관련 정보와 소스는 마음대로 활용하셔도 좋습니다. 다만 쓰시기 전에 통보 정도는 해주시는 것이 예의 일것 같습니다. 질문이나 오류 수정은 siseong@gmail.com 으로 주세요. 감사합니다.

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

by digipine posted Nov 02, 2017
?

Shortcut

PrevPrev Article

NextNext Article

Larger Font Smaller Font Up Down Go comment Print
?

Shortcut

PrevPrev Article

NextNext Article

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 •