加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift 3 发送 HTTP 请求函数

发布时间:2020-12-14 02:30:48 所属栏目:百科 来源:网络整理
导读: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 HttpS
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
    }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读