UIApplicationDelegate 启动选项介绍

1
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // Override point for customization after application launch.
  return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
  // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
  // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
  // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
  // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
  // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
  // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
  // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

每个iOS app的入口都是

1
- application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

当app启动完成,准备运行时,application会调用自己的这个代理方法。

一个app除了点击图标进行启动,还有一些其他方式调用一个app。区别不同启动方式,就需要用到launchOptions. 与userInfo 字典相似,-application:didFinishLaunchingWithOptions: 可以通过launchOptions获取启动信息的key。

通过URL启动

1
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"app://..."]];

http://URL 会调用Safari, mailto://URL 会打开邮箱, tel://URL 会拨打电话。

这种情况下launchOptionsUIApplicationLaunchOptionsURLKey

app通过URL调用时,还可以有一些系统信息。 当通过UIDocumentInteractionController 或者 AirDrop 调用时,launchedOptions 会被设置为:

UIApplicationLaunchOptionsSourceApplicationKey: key值是一个NSString,表示要调用你app的app bundle ID

UIApplicationLaunchOptionsAnnotationKey: key可以存储property-list 对象。

1
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"Document" withExtension:@"pdf"];
if (fileURL) {
  UIDocumentInteractionController *documentInteractionController =
  [UIDocumentInteractionController interactionControllerWithURL:fileURL];

  documentInteractionController.annotation = @{@"foo": @"bar"};
  [documentInteractionController setDelegate:self];
  [documentInteractionController presentPreviewAnimated:YES];
}

推送消息调用

远程推送

远程推送消息调用时,launch option 会是 UIApplicationLaunchOptionsRemoteNotificationKey

1
- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // ...

    if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
       [self application:application didReceiveRemoteNotification:launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]];
    }
}

本地推送

本地推送launch options 会是 UIApplicationLaunchOptionsLocalNotificationKey

1
@import AVFoundation;
@interface AppDelegate ()
@property (readwrite, nonatomic, assign) SystemSoundID localNotificationSound;
@end

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{     
    if (application.applicationState == UIApplicationStateActive) {         
   UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:notification.alertAction                                                               message:notification.alertBody                                                                 delegate:nil
                                             cancelButtonTitle:NSLocalizedString(@"OK", nil)                                                otherButtonTitles:nil];         
   if (!self.localNotificationSound) {             
        NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"Sosumi"                                                                        withExtension:@"wav"];             
     AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &_localNotificationSound);      }         
    AudioServicesPlaySystemSound(self.localNotificationSound);         
    [alertView show];     
  }
}
- (void)applicationWillTerminate:(UIApplication *)application {     
  if (self.localNotificationSound) {         
      AudioServicesDisposeSystemSoundID(self.localNotificationSound);     
  }
}

位置事件调用

当由手机位置变动,调用app时,launch option 会是 UIApplicationLaunchOptionsLocationKey, key 是一个NSNumber 包含一个Boolean。

1
@import CoreLocation;
@interface AppDelegate () <CLLocationManagerDelegate>
@property (readwrite, nonatomic, strong) CLLocationManager *locationManager;
@end

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {     
  // ...     
  if (![CLLocationManager locationServicesEnabled]) {         
  [[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Location Services Disabled", nil)                                  message:NSLocalizedString(@"You currently have all location services for this device disabled. If you proceed, you will be asked to confirm whether location services should be reenabled.", nil)                                    
                             delegate:nil                           
                    cancelButtonTitle:NSLocalizedString(@"OK", nil)                                                otherButtonTitles:nil] show];     
   }
   else {         
       self.locationManager = [[CLLocationManager alloc] init];         
       self.locationManager.delegate = self;         
       [self.locationManager startMonitoringSignificantLocationChanges];     
   }     
   if (launchOptions[UIApplicationLaunchOptionsLocationKey]) {         
   [self.locationManager startUpdatingLocation];     
   }
}

Newsstand

launch option 会是 UIApplicationLaunchOptionsNewsstandDownloadsKey, 提示用户有新的Newsstand可以下载

蓝牙调用

iOS 7 中蓝牙分主从关系,所以对应的launch option key有两种

UIApplicationLaunchOptionsBluetoothCentralsKey

UIApplicationLaunchOptionsBluetoothPeripheralsKey

1

@import CoreBluetooth;
@interface AppDelegate () <CBCentralManagerDelegate>
@property (readwrite, nonatomic, strong) CBCentralManager *centralManager;
@end

self.centralManager = [[CBCentralManager alloc] initWithDelegate:self
                                                         queue:nil
                                                         options:@{CBCentralManagerOptionRestoreIdentifierKey:(launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey] ?: [[NSUUID UUID] UUIDString])}];
if (self.centralManager.state == CBCentralManagerStatePoweredOn) {     
  static NSString * const UID = @"7C13BAA0-A5D4-4624-9397-15BF67161B1C"; // generated with `$ uuidgen`     
  NSArray *services = @[[CBUUID UUIDWithString:UID]];     
  NSDictionary *scanOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};     
  [self.centralManager scanForPeripheralsWithServices:services options:scanOptions];
}

参考链接