快速从Web抓取函数返回字符串 [英] Return a string from a web scraping function in swift
问题描述
好,所以我正在抓取网页的一些基本数据.我想将我的代码重构到另一个类,并从检索到的内容中返回一个字符串,但是异步函数很难实现,因此我是新手.
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.
我现在意识到该函数无法返回字符串,但是我还不太清楚如何配置完成处理程序以及如何使用完成处理程序从主类中调用函数.
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.
非常感谢您的帮助.
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
}
推荐答案
从本质上讲,您将需要从可以处理 just 返回值的主类中为该函数提供一个完成处理程序.玩家名称(或没有).您可以将函数更改为不具有返回值,但可以接受作为完成处理程序的第二个参数:
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"
}
}
}
这篇关于快速从Web抓取函数返回字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!