swift 3 发送 HTTP 请求函数

前端之家收集整理的这篇文章主要介绍了swift 3 发送 HTTP 请求函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_1@private func HttpPost(requestURL:String,postString:String) -> [String : AnyObject] { return HttpSync(requestURL: requestURL,postString: postString,method: "POST"); } private func HttpGet(requestURL:String)->[String : AnyObject]{ return HttpSync(requestURL: requestURL,postString: "",method: "GET"); } private func HttpSync(requestURL:String,postString:String,method:String)->[String : AnyObject]{ var request = URLRequest(url: URL(string:requestURL)!) request.setValue("application/x-www-form-urlencoded; charset=utf-8",forHTTPHeaderField: "Content-Type") request.setValue("application/json; charset=utf-8",forHTTPHeaderField: "Accept") if(HttpMeta.Token != ""){ request.setValue("BEARER " + HttpMeta.Token,forHTTPHeaderField: "Authorization"); } request.httpMethod = method request.httpBody = postString.data(using: String.Encoding.utf8); // print(request.debugDescription) var result:[String:AnyObject] = [:]; let semaphore = DispatchSemaphore(value:0) let task = URLSession.shared.dataTask(with: request) { data,response,error in guard let data = data,error == nil else { //print(error ?? <#default value#>) return } do { print(data.debugDescription) print(response.debugDescription) let responSEObject = try JSONSerialization.jsonObject(with: data,options: JSONSerialization.ReadingOptions.allowFragments) result = (responSEObject as? [String : AnyObject])!; print(result) // print(responSEObject) } catch let jsonError { print(jsonError.localizedDescription) // print("json error: \(jsonError.localizedDescription)") } semaphore.signal() } task.resume() _ = semaphore.wait(timeout: .distantFuture) return result }

猜你在找的Swift相关文章