func postRequest(urlStr: String,body: String) -> URLRequest? {
let method: HTTPMethod = LoginSessionManager.shared.isLogin() ? .post : .get
let postData = APIUtils.getAuthKey() ?? ""
guard var request = try? URLRequest.init(url: urlStr, method: method) else {
return nil
}
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpBody = Data(postData.utf8)
return request
}
接下來使用WKWebView發(fā)起請求就可以了
var request = self.postRequest(urlStr: urlString, body: APIUtils.getAuthKey() ?? "")
request?.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
if (request != nil) {
self.webView.load(request!)
}
APIUtils.getAuthKey() ?? "" 是要傳到服務(wù)器的參數(shù)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") 這句話比較重要, 沒有的話容易失敗.