이 함수에서는 completionHandler를 사용하지만 여러 for 루프 (아래)에 중첩되어 있습니다. 문제는 핸들러가 루프가 실행될 때마다 호출되는 반면, 전체 함수가 처리를 완료하면 핸들러가 Set
으로 전달 되기만하면됩니다. 루프 외부에 배치하면 너무 일찍 호출되어 비어 있습니다. 내가 여기서 뭘해야하지?루프 내부에서 completionHandler를 배치 할 위치는 어디입니까?
지금 나는 그것을 테스트하는 콘솔에 인쇄 할 때 인쇄 : 설정 항목 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
@GarySabo 여기서'IDs' 세트를 삽입하고 있습니까? 'setOfIDs'는'IDs'라고 생각합니까? –