【发布时间】:2019-03-04 14:59:24
【问题描述】:
向我们的 NGINX 服务器发送 POST 请求与 URLRequest 和 URLSession.shared.dataTask 配合使用效果很好。
我可以登录到我的应用程序,但是当我尝试 GET 请求时,我的服务器没有日志表明请求到达了他。最后我得到超时错误。重要的是,我使用的是 https。我还尝试将 http 用于 GET 请求。在我的 NGINX 服务器上,我仅将 TLS 设置为 1.2(我不是系统专家,我在 nginx cfg 文件中这样做了。
错误域=NSURLErrorDomain 代码=-1001 "Zeitüberschreitung bei der Anforderung。" UserInfo={NSUnderlyingError=0x60400005abe0 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://myurl, NSErrorFailingURLKey=https://myurl, _kCFStreamErrorDo _kCFStreamErrorCodeKey=-2102, NSLocalizedDescription=Zeitüberschreitung bei der Anforderung.}
我确信 URLRequest 和 URLSession 的代码是正确的,因为对于 localhost 和我们的开发环境,我没有任何这些问题。
这是我创建URLRequest的代码
private func buildUrlRequest(jsonObject:[String: Any], connectionType:ConnectionTypes, url:String) -> NSMutableURLRequest? {
let jsonDataSerialized:Data
do {
jsonDataSerialized = try JSONSerialization.data(withJSONObject: jsonObject)
} catch {
return nil
}
var request:NSMutableURLRequest
if nextData {
request = URLRequest(url: URL(string: self.nextRequestPage)!) as! NSMutableURLRequest
} else {
let tString = self.mBaseUrl + url
if let encoded = tString.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed),
var finalurl = URL(string: encoded)
{
if connectionType == .GET {
var tString:String
tString=finalurl.absoluteString
tString = tString.replacingOccurrences(of: "https", with: "http")
finalurl = URL(string:tString)!
}
request = URLRequest(url: finalurl) as! NSMutableURLRequest
} else {
return nil
}
}
request.httpMethod = connectionType.rawValue // i am using enum here
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("no-cache)", forHTTPHeaderField: "Cache-Control")
request.httpBody = jsonDataSerialized
if mUser != nil && mUser.getSessionId() != nil {
request.addValue("Token " + mUser.getSessionId()!, forHTTPHeaderField: "Authorization")
}
request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 30.0
return request
}
这就是我创建任务的方式...在我使用的方法主体之后task.resume()
let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in .... (and so on)
我花了几个小时来解决这个问题......但我不知道。 我不确定问题是服务器配置还是 Swift 代码...
【问题讨论】:
-
顺便说一句,你不需要
NSMutableURLRequest,你可以在Swift中保持URLRequest的值。此外,您可以使用URLComponents更轻松地构建您的 URL。 -
谢谢,是的,我知道,但是在尝试周围的东西时,我也尝试了 NSMutable... ;)
标签: ios swift nginx urlsession urlrequest