Ajil O. Ajil O. - 1 month ago 12
iOS Question

dispatch async code error - Objective C

I am new to Objective C but have been working on Swift for a while now. I assumed Objective c to be logically similar to swift. I have to present an alert controller while I am processing a json data request; so I had to use dispatch async to get it to work in swift. Here's the code I used in Swift:

func alertMessage(message : String) -> Void {
let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(okAction)
dispatch_async(dispatch_get_main_queue(),{
self.presentViewController(alert, animated: true, completion: nil)
})
}


But I tried to do the same thing in objective C like so

- (void)alertMessage : (NSString*) message {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:NULL];
[alert addAction:okAction];
[dispatch_async(dispatch_get_main_queue(), ^(void){
[self presentViewController:alert animated:true completion:NULL];
})];
}


I'm getting an error "expected identifier". What am I doing wrong?

Answer

Its just syntax error. Try following

- (void)alertMessage : (NSString*) message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:NULL];
    [alert addAction:okAction];

    dispatch_async(dispatch_get_main_queue(), ^(void){
        [self presentViewController:alert animated:true completion:NULL];
    });

}
Comments