-1

The completion handler code is not getting executed. while i debug the code its coming till the session.datatask and after that its not getting into the completion handler. we are actually migrating this project from objectivec to swift. i am not sure if the request generated is hitting the django or not. how to debug further. after the datatask the control exits the if request loop and there is smooth execution without any error. but the data is not fetched from DB.

func makeRequest(_ url: String?, path: String?, httpMethod: String?, httpBody httpBoday: Data?, completion: @escaping (_ result: [AnyHashable : Any]?, _ error: Error?) -> Void) {
        let headers = [
            "cache-control": "no-cache",
            "Authorization": "Token f491fbe3ec54034d51e141e28aaee87d47bb7e74"
        ]
        var request: URLRequest? = nil
        if let url = URL(string: "\(url ?? "")\(path ?? "")") {
            request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
        }
        request?.httpMethod = httpMethod ?? ""
        request?.allHTTPHeaderFields = headers
        let configuration = URLSessionConfiguration.default
        configuration.httpCookieStorage = nil
        configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
        if #available(iOS 11.0, *) {
            configuration.waitsForConnectivity = false
        }
        let session = URLSession(configuration: configuration)
        //        let session = URLSession.shared
        var task: URLSessionDataTask? = nil
        print ("Request =======>",request)
        if let request = request {
            task = session.dataTask(with: request , completionHandler: { data, response, error in
                            //.dataTask(with: request, completionHandler: { data, response, error in
               print ("testing******************")
                var result: Any? = nil
                if error != nil {
                    if let error = error {
                        print("\(error)")
                    }
                    if completion != nil {
                        completion(nil, error)
                    }
                } else
                {
                    var string: String? = nil
                    if let data = data {
                        string = String(data: data, encoding: .utf8)
                    }
                    string = self.string(byRemovingControlCharacters: string)

                    do {
                        if let data = string?.data(using: .utf8) {
                            result = try JSONSerialization.jsonObject(with: data, options: []) as!  [AnyHashable : Any]
                             print ("Result ===============>",result)
                        }
                    } catch {
                        print("Error while getting the data from json object")
                    }
                    DispatchQueue.main.async() {
                        if completion != nil {
                            completion(result as! [AnyHashable : Any], error)
                        }
                    }
                }
            })
        }
        else
        {
            print("Inside the else block of request")
        }
        task?.resume()
    }
uma
  • 9
  • 1
  • 6
  • Why is almost everything optional? This looks pretty much like literally translated Objective-C code. Please learn how to declare non-optional local variables in Swift.Before passing all that configuration stuff try the network request with `URLSession.shared`. And the way to create the URL looks quite strange, too. Is the URL valid?. Use the debugger, set breakpoints. – vadian Sep 12 '19 at 08:23
  • Horrible translation. Once again did you validate the compounded URL? – vadian Sep 12 '19 at 08:47
  • Vadian - This is literal translation from objective c only. i mean automatic translation. just fixing the bugs where ever required.This request is working fine from postman. I tried it even without configuration it was still not working. Actually my code was not having configuration details. but just searched for the solution and tried configuration. but still in vain. – uma Sep 12 '19 at 08:51
  • I understand what you're saying but it seems that you don't understand what I'm saying . And please don't [repost questions](https://stackoverflow.com/questions/57887096/after-urlsession-shared-datatask-its-either-not-returning-error-or-success). Improve your question. – vadian Sep 12 '19 at 09:02
  • sure, since i didnt get any answers i just reposted the question in more clear phase – uma Sep 12 '19 at 09:23

1 Answers1

0

This line is your problem:

if let url = URL(string: "\(url ?? "")\(path ?? "")") {
   request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
}

It needs to be like this:

guard let urlString = url else { return }
guard let path = path else { return }
if let requestURL = URL(string: "\(urlString)\(path)" {
   request = URLRequest(url: requestURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
}

Also, shouldn't make a difference, but you have 2 different cachePolicies. Also, you're not using the httpBody anywhere. I suppose your request doesn't need it, but thought I would remind you to take a look.

Starsky
  • 1,829
  • 18
  • 25
  • But at least the ```if let requestURL``` is true and you have an actual ```request```? – Starsky Sep 12 '19 at 09:39
  • Just noticed: why you're checking the completion against nil? ```if completion != nil``` Get rid of that check and just call your ```completion``` – Starsky Sep 12 '19 at 09:43
  • Yes requestURL has the URL which is actually working fine – uma Sep 12 '19 at 09:50