在Swift中使用GCD按顺序打印下载的数据

时间:2015-06-17 03:17:15

标签: swift

我正在尝试在消息" second"之前打印下载的返回消息。基本上,一旦消息被下载,它应该打印,然后是" second"信息。每次代码运行时,第二条消息都会打印,然后返回returnMessage,因为返回消息需要一些下载。是否可以允许返回消息在完成后触发,然后在每次运行代码时触发第二条消息?

    var returnMessage: String? = ""
    var downloadGroup = dispatch_group_create()
    dispatch_async(utility.GlobalUtilityQueue){
        dispatch_group_enter(downloadGroup)

        service.executeQuery(query, completionHandler: { (ticket: GTLServiceTicket!, object: AnyObject!, error: NSError!) -> Void in

            // Process the response

            let json = JSON(object.JSON)


            returnMessage = json["message"].string
            println("\(returnMessage)") // print first

        })

            dispatch_group_leave(downloadGroup)


        dispatch_group_notify(downloadGroup, self.utility.GlobalMainQueue) { 

        println("second")//should print second
        }
    }

1 个答案:

答案 0 :(得分:0)

问题是dispatch_group_leave应该 completionHandler executeQuery

var returnMessage: String? = ""
let downloadGroup = dispatch_group_create()
dispatch_async(utility.GlobalUtilityQueue){
    dispatch_group_enter(downloadGroup)

    service.executeQuery(query) { ticket, object, error in

        // Process the response

        let json = JSON(object.JSON)

        returnMessage = json["message"].string
        println("\(returnMessage)") // will print first

        dispatch_group_leave(downloadGroup)
    }

    dispatch_group_notify(downloadGroup, self.utility.GlobalMainQueue) { 
        println("second")//will print second
    }
}

显然,这不是您使用调度组的情况(通常只有在您多次进入和离开时才这样做)。此外,外部dispatch_async可能是不必要的(您正在调用异步方法,因此无需将其分配给某个后台队列)。但我认为这更像是一个学术问题,所以希望这会有所帮助。