Home Ask Login Register

Developers Planet

Your answer is one click away!

user3069232 February 2016

scheduling one task after another BUT with sessions on board Swift

Trying to understand how I can schedule one task behind the other, looked at GCD and NSOperations, but both seem to be at an abstraction to far removed from the core code; part of which executes on its very own thread!

I tried this code which was the most obvious I could find...

    let date = NSDate()
    print("getting Links \(date)")

    let operationQueue: NSOperationQueue = NSOperationQueue.mainQueue()
    let completionBlockOperation: NSBlockOperation = NSBlockOperation.init(
        block: {

    let workerBlockOperation:NSBlockOperation = NSBlockOperation.init(
        block: {

Now reportFini does next to nothing ...

func reportFini() {
    let date = NSDate()
    print("got Links \(date)")

But getLinks is more complex, using sessions... in nutshell it runs

    let request = NSMutableURLRequest(URL: NSURL(string: "https://blah")!)
    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    request.addValue("application/json",forHTTPHeaderField: "Content-Type")
    request.addValue("path", forHTTPHeaderField: lePath)
    request.addValue("settings", forHTTPHeaderField: "requested_visibility\": \"public\"}")

    var nodeA:NSMutableDictionary? = ["path":lePath]
    let nodeB:NSMutableDictionary? = ["requested_visibility":"public"]
    nodeA!.setValue(nodeB, forKey: "settings")

    do {
        let jsonData = try NSJSONSerialization.dataWithJSONObject(nodeA!, options: [])
        request.HTTPBody = jsonData
    } catch {
        completion(string: nil, error: error)
    var string2Return = ""
    var stringPath = ""
    let task = session.dataTaskWithRequest(request, comp        


user3069232 February 2016

Managed to solve this; using GCD & KVO, but not to manage the sessions; to manage a counter, and than throw a trigger by changing a monitored KVO value. A good solution, you tell me.

public class SynchronizedInt<T> {
private var blob:Int = 0
private let accessQueue = dispatch_queue_create("SynchronizedIntAccess", DISPATCH_QUEUE_SERIAL)

public func pending(queue2go:T)  {
    dispatch_sync(self.accessQueue) {
        self.blob = queue2go as! Int

public func fulfilled() -> Bool {
    dispatch_sync(self.accessQueue) {
        self.blob = self.blob - 1
    if self.blob == 0 {
        return true
    } else {
        return false

public func copy() -> Int {
    return self.blob


Which I am using to keep track of the sessions launched, so I can notified when they all complete. The completion I track in the completion blocks, each of which checks to see if it was the final one. Beyond that I used a KVO of sorts based on the first Swifty solution presented here.


Post Status

Asked in February 2016
Viewed 1,332 times
Voted 8
Answered 1 times


Leave an answer

Quote of the day: live life