标签:MyHttp completionHandler URLSession request SwiftUI https let data
1 自定义MyHttp类
class MyHttp: NSObject, URLSessionDelegate { // 使用URLSession请求数据 func httpGet(request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) { let configuration = URLSessionConfiguration.default let session = URLSession(configuration: configuration, delegate: self, delegateQueue:OperationQueue.main) let dataTask = session.dataTask(with: request, completionHandler: completionHandler) //使用resume方法启动任务 dataTask.resume() } func urlSession(_ session:URLSession, didReceive challenge:URLAuthenticationChallenge, completionHandler:@escaping (URLSession.AuthChallengeDisposition,URLCredential?) -> Void) { guard challenge.protectionSpace.authenticationMethod == "NSURLAuthenticationMethodServerTrust"else { return } let credential = URLCredential.init(trust: challenge.protectionSpace.serverTrust!) completionHandler(.useCredential,credential) } }
2. 调用MyHttp发送https请求
let myhttp = MyHttp() var request = URLRequest(url: URL(string: "https://test.aaaa.cn/login")!) request.httpMethod = "POST" request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.allHTTPHeaderFields = ["User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;)","Referer":"https://test.aaaa.cn/"] request.httpBody = "{\"user\":\"zhangsan\", \"pwd\":\"123456\"}".data(using: .utf8) myhttp.httpGet(request: request, completionHandler: {(data, response, error) -> Void in if error != nil{ print(error?.localizedDescription) }else{ let str = String(data: data!, encoding: String.Encoding.utf8) print("访问成功,获取数据如下:") print(str) } })
标签:MyHttp,completionHandler,URLSession,request,SwiftUI,https,let,data 来源: https://www.cnblogs.com/ziwuxian/p/16288673.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。