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 •

List of Articles
No. Subject Author Date Views
56 [macOS, iOS] 개발자 정보 확인하는 명령어 digipine 2023.03.23 619
55 iOS - Socket Nagle 알고리듬 OFF digipine 2017.11.01 682
54 iOS - Objective-C 남아있는 메모리 공간 확인 방법 digipine 2017.11.01 707
53 macOS Daemon 관련 시스템 폴더 목록 lizard2019 2024.03.08 726
52 Core Audio를 사용하여 macOS에서 Audio를 Capture하는 코드 digipine 2024.04.19 751
51 iOS - Thread Loop 내에서 UI 업데이트 방법 digipine 2017.11.01 781
50 iOS - Objective-C Callback for C++ digipine 2017.11.01 787
49 Apple AppStore App Review 시 Reject 피하기 위한 방법 digipine 2017.11.02 807
48 [iOS] Audio Session Setting digipine 2021.11.26 838
47 Firebase 'GoogleUtilities/GULURLSessionDataResponse.h' file not found Error Fix lizard2019 2023.07.04 840
46 Concurrent vs Serial DispatchQueue: Concurrency in Swift explained lizard2019 2021.04.16 843
45 iOS - NSURLConnection로 다중 다운로드 구현 digipine 2017.11.01 859
44 [macOS] 현재 사용 중인(열려있는) 포트 확인하고 Close 하기 digipine 2022.10.24 868
43 iOS - NSString 와 NSData 간의 데이터 상호 변환 digipine 2017.11.01 880
42 iOS - Query string을 Decode 하는 소스 digipine 2017.11.01 933
41 [iOS] 개발자를 위한 iOS 15의 새로운 기능 file digipine 2021.11.04 937
40 [MacOS] Terminal 에서 zsh compinit: insecure directories 경고 제거하기 lizard2019 2021.04.30 982
39 iOS , MacOS, iPhone용 GZipStream class 구현하기 digipine 2017.11.01 1004
38 iOS - View 이동 전환 하기 총정리 digipine 2017.11.01 1031
37 The distance estimate iBeacon signal strength lizard2019 2019.10.25 1107
Board Pagination Prev 1 2 3 Next
/ 3