顯示具有 exception 標籤的文章。 顯示所有文章
顯示具有 exception 標籤的文章。 顯示所有文章

2012年10月8日 星期一

iOS6 permissions [Contacts]

On iOS6, apple introduce new privacy control, user can control the accessment of contact and calender by each app. So, in the code side, you need to add some way to request the permission. In iOS5 or before, we can always call
ABAddressBookRef addressBook = ABAddressBookCreate();
to get the addressbook without any problem, but in iOS6, if you don't have permission, this call will just return empty pointer. That why we need to change the method to get ABAddressBookRef.

__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // we're on iOS 6
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
        accessGranted = granted;
        dispatch_semaphore_signal(sema);
    });
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    dispatch_release(sema);  
}
else { // we're on iOS 5 or older
    accessGranted = YES;
}

if (accessGranted) {
    // Do whatever you want here.
}
In the code,semaphore is used for blocking until response, while ABAddressBookRequestAccessWithCompletion will ask for permission if the app didn't ask before. Otherwise it will just follow the settings in Settings-Privacy-Contact.

2012年4月29日 星期日

[iOS] Exception catching

Exception catching is essential in developing application in .net framework and java.
While in Objective-C, it is much less powerful and shouldn't rely on it, as usually it just crash and didn't catch anything. Yet, it is still a plus if you really catch something.

Usage is really simple
@try
{
    Function_You_Want_To_Catch_Exception;
}
@catch (NSException* exception)
{
   Do_Thing_After_Exception_Caught;
}


One example is to put it in main.m, in order to catch any uncaught exception.
int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = -1;
    @try {
        retVal = UIApplicationMain(argc, argv, nil, nil);
    }
    @catch (NSException* exception) {
        NSLog(@"Uncaught exception: %@", exception.description);
        NSLog(@"Stack trace: %@", [exception callStackSymbols]);
    }
    [pool release];
    return retVal;
}
which shows how to catch all uncatched exception in the app.

Another usage is when you like "exception programming", you can raise your own exception, by using [NSException raise:format:] and catch it with above code.
Example:

[NSException raise:NSInvalidArgumentException format:@"Foo must not be nil"];

There are several exception name already defined by apple here. but if you want to use your own, put a NSString there is fine.