Swift: return result from inside dispatch_async

So, I have a block of code that doesn't work. This is due to the fact that he found zero while trying to expand an optional value. This is because it is initialized inside an asynchronous method. My question is: how can I hold back on returning a function until it gets 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
        }
    }
}
+4
source share
1 answer

If you want to wait for the results of the block, just replace dispatch_asyncwith 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 ensures that the method will not be returned until the URL content is obtained as a result.

+1
source

All Articles