从swift中的web抓取函数返回一个字符串

时间:2021-04-09 16:04:30

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 asynchronous function and I'm new with swift.

好的,我正在抓取网页的一些基本数据。我想将我的代码重构为另一个类,并从我检索的内容中返回一个字符串,但是使用异步函数很难,而且我是swift的新手。

I now realize that this function is incapable of returning a string but I can't quite figure out how to configure the completion handler and how to call the function after from the main class using the completion handler.

我现在意识到这个函数无法返回一个字符串,但我无法弄清楚如何配置完成处理程序以及如何使用完成处理程序从主类调用该函数。

Any help would be greatly appreciated, thanks.

非常感谢任何帮助,谢谢。

func getNameFromProfileUrl(profileUrl: NSURL) -> String {

        var playerName = ""

        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("<title>")


                var statusArray = urlContentArray[1].componentsSeparatedByString("</title>")

                playerName = statusArray[0] as! String

            }

        })
        task.resume()
        return playerName
    }

1 个解决方案

#1


0  

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("<title>")
            var statusArray = urlContentArray[1].componentsSeparatedByString("</title>")
            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"
        }
    }
}

#1


0  

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("<title>")
            var statusArray = urlContentArray[1].componentsSeparatedByString("</title>")
            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"
        }
    }
}