Return a string from a web scraping function in swift

前端 未结 1 1012
星月不相逢
星月不相逢 2021-01-26 12:41

Ok so I am scraping some basic data of a web page. I wanted to refactor out my code to another class and return a string from what I retrieved but it is difficult with the async

1条回答
  •  有刺的猬
    2021-01-26 13:04

    Essentially, you'll want to provide a completion handler to this function from the main class that can handle just the return of the player name (or not). You'd change the function to not have a return value, but to accept a second parameter that is a completion handler:

    func getNameFromProfileUrl(profileUrl: NSURL, completionHandler: (String?) -> Void) {
        let task = NSURLSession.sharedSession().dataTaskWithURL(profileUrl, completionHandler: { (data, response, error) -> Void in
            if error == nil {
                var urlContent = NSString(data: data, encoding: NSUTF8StringEncoding) as NSString!
                var urlContentArray = urlContent.componentsSeparatedByString("")
                var statusArray = urlContentArray[1].componentsSeparatedByString("")
                let playerName = statusArray[0] as? String
    
                completionHandler(playerName)
            } else {
                completionHandler(nil)
            }
        })
        task.resume()
    }
    

    From your main class, you'd then call it with something like this:

    myWebScraper.getNameFromProfileUrl(profileURL) { playerName in
        // always update UI from the main thread
        NSOperationQueue.mainQueue().addOperationWithBlock {
            if let playerName = playerName {
                playerNameField.text = playerName
            } else {
                playerNameField.text = "Player Not Found"
            }
        }
    }
    

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