Reputation: 1132
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
}
}
}
Upvotes: 4
Views: 1934
Reputation: 727047
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.
Upvotes: 1