0

I need to return parseResult (String) from the closure as the function result. How can i do it in Swift? The parseResult value is not not within the range of function.

import Kanna

class Parse {

    class func parseFromWeb(parseUrl: String, xpath: String) {
        let url = URL(string: parseUrl)!
        let task = URLSession.shared.dataTask(with: url, completionHandler: { ( data , response , error ) in

            DispatchQueue.main.async{
                var serverString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

                if let doc = Kanna.HTML(html: String(describing: serverString), encoding: String.Encoding.utf8) {
                    for parseResult in doc.xpath(xpath) {
                        print(parseResult)
                    }

                }
            }
        })
        task.resume()
        print("task.resume()")
    }

}
Andreas Oetjen
  • 9,889
  • 1
  • 24
  • 34
  • you need to use a completionHandler, you cannot return because you call async code which finishes after you have already returned from the function – Scriptable Feb 22 '18 at 08:14
  • 1
    Please refer to this article: https://medium.com/ios-os-x-development/managing-async-code-in-swift-d7be44cae89f – Dominik Bucher Feb 22 '18 at 08:19

1 Answers1

1

Add a completion handler to your method :

class Parse {

class func parseFromWeb(parseUrl: String, xpath: String, completionHandler: (String?) -> ()) {
    let url = URL(string: parseUrl)!
    let task = URLSession.shared.dataTask(with: url, completionHandler: { ( data , response , error ) in

        DispatchQueue.main.async{
            var serverString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)

            if let doc = Kanna.HTML(html: String(describing: serverString), encoding: String.Encoding.utf8) {
                for parseResult in doc.xpath(xpath) {
                    // Call it here as this
                    comlpetionHandler(parseResult)
                    print(parseResult)
                }

            }
        }
    })
    task.resume()
    print("task.resume()")
}

}

then you can use it like this:

self.parseFromWeb(parseUrl: yourUrl, xpath: yourPath) { (parseResult) in
        //use parse result here
}

Hope it helps!!

Agent Smith
  • 2,873
  • 17
  • 32