当我的实际设备处于 3G 或 4G 网络时,发送帖子请求总是超时。但是,当我使用 wifi 时,服务器端会立即收到发布请求。
这是我的涉及发布请求的代码。我得到一个 Optional("The request timed out.")
。我不认为 session 长度应该是一个问题,因为它会在很长一段时间后超时并且正在发送的数据只是一个带密码的用户名。有什么想法吗?
我运行一个 flask 服务器,但我认为它不相关,所以我没有包含它的代码。
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
let url = NSURL(string: base_address + taglocation_address)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
print("starting task")
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
self.statusLabel.text = error?.localizedDescription
print(error?.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary
print("doing something")
if let responseJSON = json as? [String: String] {
print(responseJSON)
self.statusLabel.text = responseJSON["status"]
}
} catch let error as NSError {
self.statusLabel.text = error.localizedDescription
print(error)
}
}
task.resume()
}
最佳答案
在您的 NSMutableURLRequest
对象中,尝试添加 allowsCellularAccess
属性并将其设置为 true。请参阅下面的代码。
if let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted) {
let url = NSURL(string: base_address + taglocation_address)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
request.allowsCellularAccess=true //Add this line
print("starting task")
let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
self.statusLabel.text = error?.localizedDescription
print(error?.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary
print("doing something")
if let responseJSON = json as? [String: String] {
print(responseJSON)
self.statusLabel.text = responseJSON["status"]
}
} catch let error as NSError {
self.statusLabel.text = error.localizedDescription
print(error)
}
}
task.resume()
}
关于ios - 帖子的神秘网络问题。 Wifi 工作,手机不,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43641410/