UIApplication一系列详解

UIApplication单例

[UIApplication sharedApplication];你的app单例对象

int main(int argc, char *argv[])
{
    @autoreleasepool {
        //UIApplicationMain函数会为你的app创建一个全局的UIApplication单例对象.
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    }
}

UIApplication应用级方法

  • 设置应用程序图标右上角的红色提醒数字
    @property(nonatomic) NSInteger applicationIconBadgeNumber;
    代码实现:
UIApplication *app = [UIApplication sharedApplication];
app.applicationIconBadgeNumber = 10;
// 创建通知对象
UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
// 注册用户通知
[app registerUserNotificationSettings:setting];
  • 设置联网指示器的可见性
    @property(nonatomic,getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible;
    代码实现:
app.networkActivityIndicatorVisible= YES;
  • 管理状态栏
    从iOS7开始,系统提供了2种管理状态栏的方式
    a.(推荐)通过UIViewController管理(每一个UIViewController都可以拥有自己不同的状态栏)在iOS7中,默认情况下,状态栏都是由UIViewController管理的,UIViewController实现下列方法就可以轻松管理状态栏的可见性和样式
    状态栏的样式   - (UIStatusBarStyle)preferredStatusBarStyle;
    状态栏的可见性  -(BOOL)prefersStatusBarHidden;
#pragma mark-设置状态栏的样式
-(UIStatusBarStyle)preferredStatusBarStyle
{
  //设置为白色
  //return UIStatusBarStyleLightContent;
  //默认为黑色
   return UIStatusBarStyleDefault;
}
#pragma mark-设置状态栏是否隐藏(否)
-(BOOL)prefersStatusBarHidden
{
  return NO;
}

注意:UINavigationController下的childViewController若要控制状态栏,需写一个UINavigationController的子类,重写childViewControllerForStatusBarStyle方法。

- (UIViewController *)childViewControllerForStatusBarStyle{
    return self.topViewController;
}

b.通过UIApplication管理(一个应用程序的状态栏都由它统一管理)如果想利用UIApplication来管理状态栏,首先得修改Info.plist的设置,添加选中行,并设置为NO即可,这篇文章中有详细介绍iOS中用application 来管理电池栏状态

![Info.plist的设置](http://upload-images.jianshu.io/upload_images/1991434-14cbcc1ebdc20116.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

代码:

//通过sharedApplication获取该程序的UIApplication对象
UIApplication *app=[UIApplication sharedApplication];
//设置状态栏的样式
//app.statusBarStyle=UIStatusBarStyleDefault;//默认(黑色)
//设置为白色+动画效果
[app setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
//设置状态栏是否隐藏
app.statusBarHidden=YES;
//设置状态栏是否隐藏+动画效果
[app setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
  • openURL:方法
    UIApplication有个功能十分强大的openURL:方法
    - (BOOL)openURL:(NSURL*)url;
    openURL:方法的部分功能有
UIApplication *app = [UIApplicationsharedApplication];
打电话  [app openURL:[NSURLURLWithString:@"tel://110"]];
发短信  [app openURL:[NSURLURLWithString:@"sms://10086"]];
发邮件  [app openURL:[NSURLURLWithString:@"mailto://[email protected]"]];
打开一个网页资源 [app openURL:[NSURL URLWithString:@"http://www.baidu.com"]];
打开其他app程序   openURL方法,可以打开其他APP。
  • 判断程序运行状态
//判断程序运行状态
  /*
   UIApplicationStateActive, 
   UIApplicationStateInactive, 
   UIApplicationStateBackground
   */
UIApplication *app = [UIApplication sharedApplication];
if(app.applicationState ==UIApplicationStateInactive){
      NSLog(@"程序在运行状态");
  }
  • 阻止屏幕变暗进入休眠状态
  //阻止屏幕变暗,慎重使用本功能,因为非常耗电。
 UIApplication *app = [UIApplication sharedApplication];
 app.idleTimerDisabled =YES;

UIApplication Delegate

当app收到干扰,例如程序运行中来电等,就会产生一些系统事件,这时UIApplicaiton会通知它的代理delegate对象,让delegate代理来处理这些系统事件。
delegate可以处理的时间包括

1.应用程序的生命周期事件(如程序启动和关闭)
2.系统事件(如来电)
3.内存警告(用处较多)

AppDelegate监听UIApplication生命周期

// AppDelegate:监听应用程序的生命周期
// 以下方法就是应用程序的生命周期方法

// 应用程序启动完成的时候就会调用AppDelegate的方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  NSLog(@"%s",__func__);
  return YES;
}
// 当应用程序失去焦点的时候调用
- (void)applicationWillResignActive:(UIApplication *)application {
   NSLog(@"%s",__func__);
}
// 当应用程序进入后台的时候调用
- (void)applicationDidEnterBackground:(UIApplication *)application {
   NSLog(@"%s",__func__);
  // 保存一些信息
}
// 当应用程序进入前台的时候调用
- (void)applicationWillEnterForeground:(UIApplication *)application {
  NSLog(@"%s",__func__);
}
// 当应用程序完全获取焦点的时候调用
// 只有当应用程序完全获取焦点的时候,才能够与用户交互
- (void)applicationDidBecomeActive:(UIApplication *)application {
   NSLog(@"%s",__func__);
}
// 当应用程序关闭的时候
- (void)applicationWillTerminate:(UIApplication *)application {

}
//收到内存警告时调用
-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application{

}

AppDelegate获取DeviceToken

DeviceToken用于上传给服务器,服务器向苹果APNs发起推送服务。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

//去除编译警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
    //注册远程通知
    if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerForRemoteNotifications)])
    {
        UIUserNotificationType types = UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound |      UIRemoteNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    }
    else
    {
        UIRemoteNotificationType types = UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound |        UIRemoteNotificationTypeBadge;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:types];
    }
#pragma clang diagnostic pop
    return YES;
}
//需要注册远程通知才会回调该方法。
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]                  stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""]);
    //上传给第三方服务器
    [[NIMSDK sharedSDK] updateApnsToken:deviceToken];
}

AppDelegate处理其他app打开自己

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        if ([url.host isEqualToString:@"safepay"]) {
            //跳转支付宝钱包进行支付,处理支付结果,此处不处理,留给需要处理的地方
            [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:nil];
        }
    }
    return result;
}

AppDelegate处理点击通知打开

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler{
    
}

AppDelegate处理屏幕旋转

// 强制旋转
+(void)transtoRotation:(UIDeviceOrientation)deviceOrientation{
    // 竖屏点击按钮 旋转到横屏
    UIDevice *device = [UIDevice currentDevice] ;
    if (UIDeviceOrientationIsLandscape(deviceOrientation)) {
        [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];
    }else{
        // 横屏点击按钮, 旋转到竖屏
        if (UIDeviceOrientationIsPortrait(device.orientation) && !UIDeviceOrientationIsPortrait([FMHelper shareHelper].deviceOrientation)) {
            [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationLandscapeLeft] forKey:@"orientation"];//这句话是防止手动先把设备置为竖屏,导致下面的语句失效.
            [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
        }else{
            [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIDeviceOrientationPortrait] forKey:@"orientation"];
        }
    }
}
#pragma mark - 屏幕旋转代理
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if ([FMHelper isAllowRotation]) {
        return UIInterfaceOrientationMaskAllButUpsideDown;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
}

-(void)application:(UIApplication *)application didChangeStatusBarOrientation:(UIInterfaceOrientation)oldStatusBarOrientation{
    NSLog(@"didChangeStatusBarOrientation");
    if ([FMHelper shareHelper].didRotationBlock) {
        [FMHelper shareHelper].didRotationBlock(self);
    }
}

-(void)application:(UIApplication *)application willChangeStatusBarOrientation:(UIInterfaceOrientation)newStatusBarOrientation duration:(NSTimeInterval)duration{
    NSLog(@"willChangeStatusBarOrientation");
    [FMHelper setDeviceOrientation:(UIDeviceOrientation)newStatusBarOrientation];
}

你可能感兴趣的:(UIApplication一系列详解)