├── .gitignore ├── LICENSE ├── Networking.playground ├── Pages │ ├── Advanced.xcplaygroundpage │ │ └── Contents.swift │ ├── Intermediate.xcplaygroundpage │ │ └── Contents.swift │ └── Simple.xcplaygroundpage │ │ └── Contents.swift └── contents.xcplayground └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## Build generated 6 | build/ 7 | DerivedData/ 8 | 9 | ## Various settings 10 | *.pbxuser 11 | !default.pbxuser 12 | *.mode1v3 13 | !default.mode1v3 14 | *.mode2v3 15 | !default.mode2v3 16 | *.perspectivev3 17 | !default.perspectivev3 18 | xcuserdata/ 19 | 20 | ## Other 21 | *.moved-aside 22 | *.xccheckout 23 | *.xcscmblueprint 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | *.ipa 28 | *.dSYM.zip 29 | *.dSYM 30 | 31 | ## Playgrounds 32 | timeline.xctimeline 33 | playground.xcworkspace 34 | 35 | # Swift Package Manager 36 | # 37 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 38 | # Packages/ 39 | # Package.pins 40 | # Package.resolved 41 | .build/ 42 | 43 | # CocoaPods 44 | # 45 | # We recommend against adding the Pods directory to your .gitignore. However 46 | # you should judge for yourself, the pros and cons are mentioned at: 47 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 48 | # 49 | # Pods/ 50 | 51 | # Carthage 52 | # 53 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 54 | # Carthage/Checkouts 55 | 56 | Carthage/Build 57 | 58 | # fastlane 59 | # 60 | # It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the 61 | # screenshots whenever they are needed. 62 | # For more information about the recommended setup visit: 63 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 64 | 65 | fastlane/report.xml 66 | fastlane/Preview.html 67 | fastlane/screenshots/**/*.png 68 | fastlane/test_output 69 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Timothy Miko 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Networking.playground/Pages/Advanced.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import PlaygroundSupport 3 | 4 | enum HTTPMethod: String { 5 | case get = "GET" 6 | case put = "PUT" 7 | case post = "POST" 8 | case delete = "DELETE" 9 | case head = "HEAD" 10 | case options = "OPTIONS" 11 | case trace = "TRACE" 12 | case connect = "CONNECT" 13 | } 14 | 15 | struct HTTPHeader { 16 | let field: String 17 | let value: String 18 | } 19 | 20 | class APIRequest { 21 | let method: HTTPMethod 22 | let path: String 23 | var queryItems: [URLQueryItem]? 24 | var headers: [HTTPHeader]? 25 | var body: Data? 26 | 27 | init(method: HTTPMethod, path: String) { 28 | self.method = method 29 | self.path = path 30 | } 31 | 32 | init(method: HTTPMethod, path: String, body: Body) throws { 33 | self.method = method 34 | self.path = path 35 | self.body = try JSONEncoder().encode(body) 36 | } 37 | } 38 | 39 | struct APIResponse { 40 | let statusCode: Int 41 | let body: Body 42 | } 43 | 44 | extension APIResponse where Body == Data? { 45 | func decode(to type: BodyType.Type) throws -> APIResponse { 46 | guard let data = body else { 47 | throw APIError.decodingFailure 48 | } 49 | let decodedJSON = try JSONDecoder().decode(BodyType.self, from: data) 50 | return APIResponse(statusCode: self.statusCode, 51 | body: decodedJSON) 52 | } 53 | } 54 | 55 | enum APIError: Error { 56 | case invalidURL 57 | case requestFailed 58 | case decodingFailure 59 | } 60 | 61 | enum APIResult { 62 | case success(APIResponse) 63 | case failure(APIError) 64 | } 65 | 66 | struct APIClient { 67 | 68 | typealias APIClientCompletion = (APIResult) -> Void 69 | 70 | private let session = URLSession.shared 71 | private let baseURL = URL(string: "https://jsonplaceholder.typicode.com")! 72 | 73 | func perform(_ request: APIRequest, _ completion: @escaping APIClientCompletion) { 74 | 75 | var urlComponents = URLComponents() 76 | urlComponents.scheme = baseURL.scheme 77 | urlComponents.host = baseURL.host 78 | urlComponents.path = baseURL.path 79 | urlComponents.queryItems = request.queryItems 80 | 81 | guard let url = urlComponents.url?.appendingPathComponent(request.path) else { 82 | completion(.failure(.invalidURL)); return 83 | } 84 | 85 | var urlRequest = URLRequest(url: url) 86 | urlRequest.httpMethod = request.method.rawValue 87 | urlRequest.httpBody = request.body 88 | 89 | request.headers?.forEach { urlRequest.addValue($0.value, forHTTPHeaderField: $0.field) } 90 | 91 | let task = session.dataTask(with: urlRequest) { (data, response, error) in 92 | guard let httpResponse = response as? HTTPURLResponse else { 93 | completion(.failure(.requestFailed)); return 94 | } 95 | completion(.success(APIResponse(statusCode: httpResponse.statusCode, body: data))) 96 | } 97 | task.resume() 98 | } 99 | } 100 | 101 | struct Post: Decodable { 102 | let userId: Int 103 | let id: Int 104 | let title: String 105 | let body: String 106 | } 107 | 108 | let request = APIRequest(method: .get, path: "posts") 109 | 110 | APIClient().perform(request) { (result) in 111 | switch result { 112 | case .success(let response): 113 | if let response = try? response.decode(to: [Post].self) { 114 | let posts = response.body 115 | print("Received posts: \(posts.first?.title ?? "")") 116 | } else { 117 | print("Failed to decode response") 118 | } 119 | case .failure: 120 | print("Error perform network request") 121 | } 122 | } 123 | 124 | PlaygroundPage.current.needsIndefiniteExecution = true 125 | 126 | -------------------------------------------------------------------------------- /Networking.playground/Pages/Intermediate.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import PlaygroundSupport 3 | 4 | enum HTTPMethod: String { 5 | case get = "GET" 6 | case put = "PUT" 7 | case post = "POST" 8 | case delete = "DELETE" 9 | case head = "HEAD" 10 | case options = "OPTIONS" 11 | case trace = "TRACE" 12 | case connect = "CONNECT" 13 | } 14 | 15 | struct HTTPHeader { 16 | let field: String 17 | let value: String 18 | } 19 | 20 | class APIRequest { 21 | let method: HTTPMethod 22 | let path: String 23 | var queryItems: [URLQueryItem]? 24 | var headers: [HTTPHeader]? 25 | var body: Data? 26 | 27 | init(method: HTTPMethod, path: String) { 28 | self.method = method 29 | self.path = path 30 | } 31 | } 32 | 33 | enum APIError: Error { 34 | case invalidURL 35 | case requestFailed 36 | } 37 | 38 | struct APIClient { 39 | 40 | typealias APIClientCompletion = (HTTPURLResponse?, Data?, APIError?) -> Void 41 | 42 | private let session = URLSession.shared 43 | private let baseURL = URL(string: "https://jsonplaceholder.typicode.com")! 44 | 45 | func request(_ request: APIRequest, _ completion: @escaping APIClientCompletion) { 46 | 47 | var urlComponents = URLComponents() 48 | urlComponents.scheme = baseURL.scheme 49 | urlComponents.host = baseURL.host 50 | urlComponents.path = baseURL.path 51 | urlComponents.queryItems = request.queryItems 52 | 53 | guard let url = urlComponents.url?.appendingPathComponent(request.path) else { 54 | completion(nil, nil, .invalidURL); return 55 | } 56 | 57 | var urlRequest = URLRequest(url: url) 58 | urlRequest.httpMethod = request.method.rawValue 59 | urlRequest.httpBody = request.body 60 | 61 | request.headers?.forEach { urlRequest.addValue($0.value, forHTTPHeaderField: $0.field) } 62 | 63 | let task = session.dataTask(with: urlRequest) { (data, response, error) in 64 | guard let httpResponse = response as? HTTPURLResponse else { 65 | completion(nil, nil, .requestFailed); return 66 | } 67 | completion(httpResponse, data, nil) 68 | } 69 | task.resume() 70 | } 71 | } 72 | 73 | let request = APIRequest(method: .post, path: "posts") 74 | request.queryItems = [URLQueryItem(name: "hello", value: "world")] 75 | request.headers = [HTTPHeader(field: "Content-Type", value: "application/json")] 76 | request.body = Data() // example post body 77 | 78 | APIClient().request(request) { (_, data, _) in 79 | if let data = data, let result = String(data: data, encoding: .utf8) { 80 | print(result) 81 | } 82 | } 83 | 84 | PlaygroundPage.current.needsIndefiniteExecution = true 85 | 86 | -------------------------------------------------------------------------------- /Networking.playground/Pages/Simple.xcplaygroundpage/Contents.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import PlaygroundSupport 3 | 4 | enum APIError: Error { 5 | case invalidURL 6 | case requestFailed 7 | } 8 | 9 | struct APIClient { 10 | 11 | typealias APIClientCompletion = (HTTPURLResponse?, Data?, APIError?) -> Void 12 | 13 | private let session = URLSession.shared 14 | private let baseURL = URL(string: "https://jsonplaceholder.typicode.com") 15 | 16 | func request(method: String, path: String, _ completion: @escaping APIClientCompletion) { 17 | guard let url = baseURL?.appendingPathComponent(path) else { 18 | completion(nil, nil, .invalidURL); return 19 | } 20 | 21 | var request = URLRequest(url: url) 22 | request.httpMethod = method 23 | 24 | let task = session.dataTask(with: request) { (data, response, error) in 25 | guard let httpResponse = response as? HTTPURLResponse else { 26 | completion(nil, nil, .requestFailed); return 27 | } 28 | completion(httpResponse, data, nil) 29 | } 30 | task.resume() 31 | } 32 | } 33 | 34 | APIClient().request(method: "get", path: "todos/1") { (_, data, _) in 35 | if let data = data, let result = String(data: data, encoding: .utf8) { 36 | print(result) 37 | } 38 | } 39 | 40 | PlaygroundPage.current.needsIndefiniteExecution = true 41 | -------------------------------------------------------------------------------- /Networking.playground/contents.xcplayground: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Swift networking examples from my blog post: [It's time to break up with your networking library for URLSession](https://tim.engineering/break-up-third-party-networking-urlsession) 2 | --------------------------------------------------------------------------------