MrGeorgeous MrGeorgeous - 4 months ago 70
Swift Question

Swift analogue of Java Thread.join()

That is how my code looks right now. I am trying to launch a thread but my code goes to recursive cycle. I would like to get my error reason from you or get Swift analogue of wonderful Java Thread.join() function which is very useful in this situation.

var ret: JSON = JSON("{\"code\":\"-3\"}")
var cont: Bool = true

dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), {

let req = Alamofire.request(.POST, "https://pornhub.com", parameters: parameters).validate().responseJSON { response in
switch response.result {
case .Success(let data):
let json = JSON(data)
print("TEST: " + ret.string!)
ret = json
case .Failure(let error):
print("TEST: " + ret.string!)
ret = (JSON("{\"code\":\"-2\"}"))
}
}

dispatch_async(dispatch_get_main_queue(), { () -> Void in

cont = false

})

})

while(cont) {
sleep(1)
}

return ret

Answer

Since you are blocking the main thread anyway why even use async in this case?

If you do want to not block the main thread (usually the UI thread and usually a very bad idea to do) you should call the method you provided in code and pass in a "completion" block. That completion block will have the ret value and will allow your process to continue. It may be a little difficult to see with that explanation, so I'll try to explain it with pseudo code:

function mainThread()
{
    var somethingINeed = firstAttempt()
    doSomethingWithReturn(somethingINeed);
}

function firstAttempt()
{
    var ret = doSomethingLong()
    return ret
}

So that just block the main thread and does your long task. Instead of that, and instead of your async with blocking, try something like this (again, pseudo code):

function mainThread()
{
    secondAttempt(method(var ret)
    {
        doSomethingWithReturn(ret);
    })
}

function secondAttempt(functionBlock)
{
    async{
        var ret = doSomethingLong()
        functionBlock(ret)
    }
}