Swift 3: URLSession / URLRequest Not Working

前端 未结 1 1122
面向向阳花
面向向阳花 2021-01-18 00:07

I am still trying to convert our application from Swift 2 over to Swift 3 because I am being forced to since all of our Apple devices are now running iOS 10.

I have

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 00:17

    If you put a breakpoint immediately after calling getUser, the URLSession task's completion handler, which runs asynchronously (i.e. generally finishes later, unless the request failed immediately or was satisfied by some cached response) may not have had a chance to be called.

    If you put a breakpoint inside the dataTask completion handler, you should see your data at that point.


    Personally, I'd make sure to give getUser a completion handler so you know when it's done:

    func getUser(completionHandler: @escaping (JSON?, Error?) -> Void) {
        let params = [
            "email":"\(preferences.string(forKey: "preference_email")!)"
        ]
    
        let requestParams: [String: Any] = [
            "action": "601",
            "params": params
        ]
    
        do {
            let requestObject = try JSONSerialization.data(withJSONObject: requestParams)
    
            var request = URLRequest(url: URL(string: "http://domain.tld/path/")!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 20)
    
            request.httpBody = requestObject
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept")
    
            let task = URLSession.shared.dataTask(with: request) {data, response, error in
                guard let data = data, error == nil else {
                    completionHandler(nil, error)
                    return
                }
    
                completionHandler(JSON(data: data), nil)
            }
    
            task.resume()
        } catch {
            completionHandler(nil, error)
        }
    }
    

    Then when you call it, you can do something like:

    getUser { json, error in
        guard let json = json else {
            print(error)
            return
        }
    
        // do something with json
        print(json)
    }
    

    And just put your breakpoint in getUser's completion handler. And remember that you have no assurances that the completion handler will run on the main queue or not, so you'll want to make sure to dispatch and UI or model updates back to the main queue.

    0 讨论(0)
提交回复
热议问题