Swift:阻止所有代码,直到函数完成执行

时间:2016-07-01 18:13:53

标签: swift semaphore

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

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)
}

1 个答案:

答案 0 :(得分:1)

您在完成处理程序中缺少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时锁定UI绝不是一个好主意。