Swift: 阻塞所有代码直到一个函数完成执行

Swift: block all code until a function finishes executing

我正在调用一个从服务中获取关键数据的函数。我希望所有代码都等到发生这种情况。我尝试使用信号量,但它似乎没有像预期的那样工作。我的代码是这样的:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    getUserById(userIDParam)
    thisShouldWait()
....

func getUserById(id: Int) -> Void {
    let semaphore = dispatch_semaphore_create(0)
    WebService.getUserById(id) { user in
        AppDelegate.CurrentUser = user
    }
}

函数:thisShouldWait() 在完成处理程序完成之前执行。所以我尝试使用信号量,但 运行 无限期。解决办法是什么?我的服务器 getUserById:

class func getUserById(userID: Int, completionHandler: (User) -> Void) -> Void {

    let semaphore = dispatch_semaphore_create(0)
    let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

    let methodParameters = []

    let url = appDelegate.URL

    let dataTask: NSURLSessionDataTask = defaultSession.dataTaskWithURL(url, completionHandler: {(data, response, error) -> Void in

        if error != nil {
        } else if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode >= 200 || httpResponse.statusCode <= 299 {
                let user: User = parseSearchResults(data)
                completionHandler(user)
            }
        }
    })

    dataTask.resume()

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}

您的完成处理程序中缺少 dispatch_semaphore_signal

let dataTask: NSURLSessionDataTask = defaultSession.dataTaskWithURL(url) { data, response, error in
    if error != nil {
    } else if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode >= 200 || httpResponse.statusCode <= 299 {
            let user: User = parseSearchResults(data)
            completionHandler(user)
        }
    }
    dispatch_semaphore_signal(semaphore) // Added
}

确保在后台线程上调用 getUserById。在完成时锁定 UI 绝不是一个好主意。