【发布时间】:2016-12-15 19:25:45
【问题描述】:
我在这个函数中使用了completionHandler,但是它嵌套在几个for循环中(如下)。问题是每次循环运行时都会调用它的处理程序,而我只希望处理程序在整个函数完成处理时传入Set。如果我将它放在循环之外,那么它会被过早地调用并且是空的。我应该在这里做什么?
现在,当我打印到控制台进行测试时,它会打印: 设置项目 1 设置项目 1、2 设置项目1、2、3等。
struct RekoRequest {
public func getRekos(rekoType: rekoCategory, handler: @escaping (Set<String>) -> Void) {
var urls = [NSURL]()
var IDs = Set<String>()
TwitterRequest().fetchTweets(searchType: "things") { result in
guard let tweets = result as? [TWTRTweet] else {print("Error in getRekos receiving tweet results from TwitterRequest.fetchTweets"); return}
for tweet in tweets {
let types: NSTextCheckingResult.CheckingType = .link
let detector = try? NSDataDetector(types: types.rawValue)
guard let detect = detector else { print("NSDataDetector error"); return }
let matches = detect.matches(in: text, options: .reportCompletion, range: NSMakeRange(0, (text.characters.count)))
for match in matches {
if let url = match.url {
guard let unwrappedNSURL = NSURL(string: url.absoluteString) else {print("error converting url to NSURL");return}
//Show the original URL
unwrappedNSURL.resolveWithCompletionHandler {
guard let expandedURL = URL(string: "\($0)") else {print("couldn't covert to expandedURL"); return}
guard let urlDomain = expandedURL.host else { print("no host on expandedURL"); return }
switch urlDomain {
case "www.somesite.com":
let components = expandedURL.pathComponents
for component in components {
if component == "dp" {
guard let componentIndex = components.index(of: component) else {print("component index error"); return}
let IDIndex = componentIndex + 1
let ID = components[IDIndex]
//Filter out Dups and add to Set
IDs.insert(ID)
handler(IDs)
print(ID) //this prints multiple sets of IDs, I only want one when the function is finished completely
}
}
break;
default:
break;
}
}
} else { print("error with match.url") }
} //for match in matches loop
} //for tweet in tweets loop
}
}
}
// Create an extension to NSURL that will resolve a shortened URL
extension NSURL
{
func resolveWithCompletionHandler(completion: @escaping (NSURL) -> Void)
{
let originalURL = self
let req = NSMutableURLRequest(url: originalURL as URL)
req.httpMethod = "HEAD"
URLSession.shared.dataTask(with: req as URLRequest)
{
body, response, error in completion(response?.url as NSURL? ?? originalURL)
}
.resume()
}
}
【问题讨论】:
-
为什么不将完成处理程序放在循环之后?
-
当我把它放在循环之后,我得到一个空集
-
@GarySabo 你在哪里插入
IDs集合?setOfIDs应该是IDs吗? -
抱歉,我稍微清理了一下代码,错过了,它是 for 组件循环中的
IDs.insert(ID)
标签: ios swift for-loop completionhandler