首页 > 解决方案 > 如何在 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()
}

标签: iosswift4

解决方案


推荐阅读