URLSessionUploadTask getting automatically cancelled instantly

前端 未结 3 1830
心在旅途
心在旅途 2020-12-17 20:49

I\'m having this weird issue in which a newly created URLSessionUploadTask gets cancelled instantly. I\'m not sure if it\'s a bug with the current beta of Xcode

3条回答
  •  再見小時候
    2020-12-17 21:19

    After struggling non-stop with this for 6 days, and after googling non-stop for a solution, I'm really happy to say I have finally figured it out.

    Turns out that, for whatever mysterious reason, the from: parameter in uploadTask(with:from:completionHandler) cannot be nil. Despite the fact that the parameter is marked as an optional Data, it gets cancelled instantly when it is missing. This is probably a bug on Apple's side, and I opened a bug when I couldn't get this to work, so I will update my bug report with this new information.

    With that said, everything I had to do was to update my buildPOSTTask method to account for the possibility of the passed dictionary to be nil. With that in place, it works fine now:

    internal func buildPOSTTask(onURLSession urlSession: URLSession, appendingPath path: String, withPostParameters postParams: [String : String]?, getParameters getParams: [String : String]?, httpHeaders: [String : String]?, completionHandler completion: URLSessionUploadTaskCompletionHandler) -> URLSessionUploadTask {
        let fullURL: URL
        if let gets = getParams {
            fullURL = buildURL(appendingPath: path, withGetParameters: gets)
        } else {
            fullURL = URL(string: path, relativeTo: baseURL)!
        }
    
        var request = URLRequest(url: fullURL)
        request.httpMethod = "POST"
    
        var postParameters: Data
    
        if let posts = postParams {
            do {
                postParameters = try JSONSerialization.data(withJSONObject: posts, options: [])
            } catch let error as NSError {
                fatalError("[\(#function) \(#line)]: Could not build POST task: \(error.localizedDescription)")
            }
        } else {
            postParameters = Data()
        }
    
        let postTask = urlSession.uploadTask(with: request, from: postParameters, completionHandler: completion)
        return postTask
    }
    

提交回复
热议问题