ios - 如何在 swift 4、usrlsession 中解决 rest api 调用的性能问题
问题描述
当我从模拟器/设备点击 api 时,从 api 响应中获取数据需要将近 18-20 秒,而在 POSTMAN 应用程序中,相同的 API 在 1.4 秒内获得响应。几乎所有 API 都会出现此问题。即使我尝试过使用 Alamofire,但同样的问题正在发生。如何解决这个问题?提前致谢!
我在网络管理器类中使用以下代码:
typealias serverResponseBlock = (_ success: Bool, _ message: String, _ dataDict: [AnyHashable: Any]) -> Void
class func createRequest(httpMethod : HTTPMethod, endPoint : String, parameters : [String : Any], completion: @escaping serverResponseBlock) -> Void {
let baseUrl = ApiConstants.kBaseUrl + ApiConstants.kPath + endPoint
var request = URLRequest.init(url: URL.init(string: baseUrl)!)
request.timeoutInterval = 60
request.httpMethod = httpMethod.rawValue
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: [])
request.addValue("Bearer \(StoredValues.Token)", forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
if error == nil{
let httpResponse = response as! HTTPURLResponse
if httpResponse.statusCode == 200 {
do {
let json = try JSONSerialization.jsonObject(with: data!)
APIManager.processResponse(responseObject: json, block: completion)
} catch {
print("error")
}
}else{
completion(false, "Could not complete your request", [:])
}
}else{
completion(false, /error?.localizedDescription, [:])
}
})
task.resume()
}
解决方案
推荐阅读
- azure - Azure IoTHub - 如何获取每台设备的使用数据
- postgresql - 对于这个模式,你如何将 postgres 扩展到数十亿行?
- qt - 使用 Docker 使用 QOffscreenSurface 进行屏幕外渲染
- javascript - onClick 功能仅在第一次反应中有效?
- java - 设计模式 - 单例和类加载器
- amazon-web-services - Velero 不会安装,“additionalProperties 不能设置为 false”
- c# - GraphServiceClient,创建 ContentVersions 以使用 GraphServiceClient
- android - 渲染多个模型时,ARCore (Sceneform) 应用程序崩溃
- python - 在python中查找两个日期之间的月数
- python - 如何创建一个伪随机数生成器程序,既可以充当魔术 8 球,又可以从一副牌中选择一张牌?