我在这个函数中使用了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()
}
}
答案 0 :(得分:0)
在for循环后调用完成处理程序。
for component in components {
if component == "dp" {
...
}
}
handler(IDs)
重要提示:
handler
应该在for循环中称为 ,但在TwitterRequest().fetchTweets()
后尾闭合。
处理空集的方法
您的IDs
正在初始化为空集。只有在满足for循环中的某些条件后,才会将值插入此集合中。如果不满足这些条件,那么您的IDs
设置将为空。
如果这是不合需要的,那么您必须更改完成处理程序或更改条件逻辑,以便始终获得非空集。
一种方法可能是在回调中设置可选项。类似的东西:
(Set<String>?) -> Void
如果IDs
为空,则使用nil
回调并让您的调用代码处理nil
设置的可能性。
另一种方法可能是创建一个枚举来封装你的结果并在你的回调中使用它。类似的东西:
<强>枚举强>
enum Result {
case success(Set<String>)
case failure
}
<强>回调强>
handler: (Result) -> Void
<强>用法强>
handler(.success(IDs))
// or
handler(.failure)
致电代码
getReckos(rekoType: .someType) { result in
switch result {
case .success(let IDs):
// Use IDs
case .failure:
// Handle no IDs
}
}