当视图控制器被解雇时,在后台发送alamofire请求

时间:2016-10-24 11:45:19

标签: swift background alamofire

我有功能,应该发送视频位置时间,当用户关闭avplayercontroller时,就在这里:

let concurrentQueue = DispatchQueue(label: "networkRequest", attributes: .concurrent)

fileprivate func sendBackgroundRequest(urlString: String, method: HTTPMethod, parameters: Parameters?) {

    let headers = createHeader()

    print(headers)

    if networkManager!.isReachable {

        concurrentQueue.async {

            let request = Alamofire.request(urlString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)

            request.responseJSON { data in

                if data.result.error == nil {
                    if data.response?.statusCode == 200 {
                        print("Success")
                    } else {
                        print(data.response?.statusCode)
                    }
                } else {
                    print(data.result.error)
                }

            }

        }

    }
}

func sendSeriesDurationTime(provider: String, fileID: String, timePosition: Int) {
    let parameters: Parameters = [
        "time_position": timePosition
    ]

    let dataUrl = "\(BASE_URL)\(PLAYED_DURATION_SLUG)\(provider)/\(fileID)"

    print(dataUrl)

    sendBackgroundRequest(urlString: dataUrl, method: .post, parameters: parameters)
}

我在 viewWillDisappear 方法中调用它。但是,当我点击"完成"播放器的按钮,它需要一些时间,在它消失之前,因为系统在alamofire响应完成之前等待。

我知道,我可以在 viewDidDisappear 方法中调用它,但这样我的UI会在另一个控制器中冻结....

1 个答案:

答案 0 :(得分:1)

我找到了答案,只需要删除

    request.responseJSON { data in

        if data.result.error == nil {
            if data.response?.statusCode == 200 {
                print("Success")
            } else {
                print(data.response?.statusCode)
            }
        } else {
            print(data.result.error)
        }

    }

所以发出了请求,但UI没有冻结,系统没有等待服务器响应。