4

So I have a block of code here which doesn't work. This is due to the fact that it found nil while trying to unwrap an optional value. Which is because it gets initialized inside the asynchronous method. My question is, how do I hold off on returning the function until it has fetched the result?

struct Domain {
    var name: String?
    var tld: String?
    var combined: String {
        get {
            return self.name!+self.tld!
        }
    }
    var whoIs: String {
        get {
            if self.whoIs.isEmpty {
                var result: String?
                dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
                    let whois_url = NSURL(string: SEARCH_URL+self.combined+"/whois")
                    result = NSString(contentsOfURL: whois_url!, encoding: NSUTF8StringEncoding, error: nil)
                    print(result!)
                })
                return result!
            }
            return self.whoIs
        }
    }
}

1 Answer 1

1

If you want to wait for the results of the block, simply replace dispatch_async with dispatch_sync:

dispatch_sync(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    let whois_url = NSURL(string: SEARCH_URL+self.combined+"/whois")
    result = NSString(contentsOfURL: whois_url!, encoding: NSUTF8StringEncoding, error: nil)
    print(result!)
})

This would ensure that the method does not return until the content of URL is fetched into the result.

Sign up to request clarification or add additional context in comments.

1 Comment

You have to make sure that you dont dispatch_sync from the same thread as to where you are dispatching the closure -> deadlock

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.