API
✢ Notes
- API is two-way in the most of time.
Use closure is a easy way to control the response from API.
func requestAPI(api: String, param: [String: Any], success: @escaping (NSDictionary?) -> Void, fail: @escaping (NSDictionary) -> Void) { guard let url = URL(string: api) else { NSLog("%@ is not exist !", api) return } var request = URLRequest(url: url) let data = JSON(param) //Dictionary -> JSON var requestData = "" //prepare request data (follow the API request define) requestData = ... ... //set-up API connection (follow the API request define) request.httpBody = requestData.data(using: .utf8, allowLossyConversion: true) request.timeoutInterval = 30 request.httpMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") //send request let task = URLSession.shared.dataTask(with: request) { (data, response, error) in guard error == nil else { NSLog("Session error: %@", String(describing: error)) return } //parse response if let dict = DICT(data!) { //JSON -> Dictionary if success { success(data) } else { fail(data) } } } task.resume() }