通知触发时播放视频

Play Video When Notification fire

我正在制作一个应用程序,其中用户 select 时间和视频。当通知触发时,我希望播放 select 视频。我怎样才能做到这一点? 这是我的通知代码。

-(void) scheduleLocalNotificationWithDate:(NSDate *)fireDate
{

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];

    localNotif.fireDate = fireDate;
    localNotif.timeZone = [NSTimeZone localTimeZone];
    localNotif.alertBody = @"Time to wake Up";
    localNotif.alertAction = @"Show me";
    localNotif.soundName = @"Tick-tock-sound.mp3";
    localNotif.applicationIconBadgeNumber = 1;
    localNotif.repeatInterval = NSCalendarUnitDay;
    NSLog(@" date %lu",kCFCalendarUnitDay);
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif]; 
}

有什么建议吗?

一旦用户打开您的本地通知,您的应用就会启动,- application:didFinishLaunchingWithOptions: of your UIApplicationDelegate will be called. The options dictionary will contain a UIApplicationLaunchOptionsLocalNotificationKey key, which contains the UILocalNotification. That should give you enough information to determine which video needs to be played, which you can do with the Media Player framework

您安排本地通知的代码看起来不错。也许你还应该在本地通知的 userInfo 属性 中添加一些数据,这样当它触发时,你可以检查 属性 并根据需要做一些不同的事情(播放特定视频)到 userInfo.

里面的数据

示例:

NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"video1" forKey:@"videoName"];
localNotif.userInfo = infoDict;

确保您还请求用户许可使用本地通知,否则本地通知将不会触发。

示例:

UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

现在您需要处理当您的应用程序处于 3 种状态时触发本地通知:前景、background/suspended 和非 运行。

该应用程序 运行 在 前台 。本地通知会在您设置的日期触发。以下委托方法将在 AppDelegate 中被系统调用:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    NSString *videoName = [notification.userInfo objectForKey:@"videoName"];
    //do something, probably play your specific video
}

该应用程序 运行 在 后台或已暂停 。向用户显示本地通知(它在您设置的日期触发)并且用户点击它。系统将在 AppDelegate 中调用与上述 (didReceiveLocalNotification) 相同的委托方法:

应用 不是 运行,向用户显示本地通知(它在您设置的日期触发)并且用户点击它。以下委托方法将在 AppDelegate 中被系统调用:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotif)
    {
       //the app was launched by tapping on a local notification
       NSString *videoName = [localNotif.userInfo objectForKey:@"videoName"];
       // play your specific video
    } else {
       // the app wasn't launched by tapping on a local notification
       // do your regular stuff here
    }
}

我建议阅读 Apple's documentation 关于使用本地通知的内容。

您可以使用 Glorfindel 的回答 中推荐的媒体播放器框架,您可以在此 Whosebug answer 中找到播放视频的示例。