I have following callback in block in Objective C
typedef void (^COMPLETION_BLOCK)(NSString *response, NSError *errorString);
+ (void)responseFromURL:(NSURL *)url completionBlock:(COMPLETION_BLOCK)completionBlock
{
__block NSError *error = nil;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSString *response = [NSString stringWithContentsOfURL:url
encoding:NSUTF8StringEncoding
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
completionBlock(response, error);
});
});
}
Here is how i call it in Objective C
[Utilities responseFromURL:NSURL URLWithString:@""] completionBlock:^(NSString *response, NSError *errorString)
{
}]
I have tried converting this in Clousers in swift here is the code
class Utilities
{
typealias COMPLETION_BLOCK = ( response : NSString, error : NSError) -> ()
func responseFromURL(url: NSURL , completionBlock:COMPLETION_BLOCK)
{
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
var e : NSError?;
dispatch_async(dispatch_get_global_queue(priority, 0))
{
var content:NSString? = NSString(contentsOfURL: url,
encoding: NSUTF8StringEncoding,
error: &e)
dispatch_async(dispatch_get_main_queue())
{
completionBlock(response: content!,error: e!);
}
}
}
}
I am not sure if this is correct conversion. Secondly how am i suppose to call the block in swift?
var urlString = String(format: BASE_URL + "%d", categoryType);
var url = NSURL(string :urlString);