在哪里记录您的iOS应用程序的打开方式和时间

时间:2014-08-22 19:04:29

标签: ios appdelegate

我想在每次用户打开我的应用时捕获数据。我知道AppDelegate.m中的所有道路最终都会导致applicationDidBecomeActive,但是有一个捕获应用程序打开的最佳做法吗?

我想知道应用程序是通过推送通知,URL请求还是直接通过应用程序图标打开的。我可以在didReceiveRemoteNotification等单独录制所有这些内容,但我认为我需要始终拥有'直接'打开记录在applicationDidBecomeActive ...但我能完全解决的唯一方法是使用OPEN_RECORDED标志,如下所示:

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

    NSDictionary* notification =
        [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];


    if (notification) {
        [self recordStat:@“remoteNotification”];
    } else {
        [self recordStat:@“directOpen”];
    }

    return YES;
}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [self recordStat:@“directOpen”];

    // Reset OPEN_RECORDED for next time
    self.OPEN_RECORDED = NO;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{

    if (application.applicationState==UIApplicationStateInactive ||
        application.applicationState==UIApplicationStateBackground)  {
        [self recordStat:@“remoteNotification”];
    } 

}


// Handle Custom URL Scheme
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    [self recordStat:@“customURL”];

    return YES;
}

-(void)recordStat:(NSString*)stat {
    if (!self.OPEN_RECORDED) { 
        // Upload the stat to my server
        // CODE HERE

        // Set the OPEN_RECORDED flag
        self.OPEN_RECORDED = YES;
    }       
}

但是国旗看起来很傻......有没有更好的办法呢?

1 个答案:

答案 0 :(得分:0)

您可以在NSUserDefaults

中撰写
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"recorded"];
[[NSUserDefaults standardUserDefaults] synchronize];

然后检查启动值你的记录方法:

if (![[NSUserDefaults standardUserDefaults] boolForKey:@"recorded"]) {
    // Not recorded
} else {
    // Launch recorded
}

我认为这种方法更好,因为您可以在另一个类(AppDelegate之外)中实现recordStat方法。您可以随处查看NSUserDefaults值。

您可以在方法applicationDidBecomeActive上记录启动类型(直接,推送通知或网址)并调用方法recordStat一次(并传递启动类型的值)。这样你就可以整理你的代码了。