来自Apple Watch的触发通知

时间:2015-05-19 03:24:35

标签: uilocalnotification apple-watch

我试图在Apple Watch上按下按钮几分钟后安排本地通知开火(我在实际设备上进行测试)。这就是我尝试它的方式:

- (IBAction)buttonPressed {
    [WKInterfaceController openParentApplication: nil  reply: nil {
}

在AppDelegate中:

- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo))reply {

}

问题是,我不知道在哪里放置通知代码。我非常确定我必须调用openParentApplication来安排它,但不知道如何。我一直在网上阅读,但没有发现任何有用的东西。

1 个答案:

答案 0 :(得分:0)

好的,你几乎就在那里:

首先这样打电话:

- (IBAction)buttonPressed {
  NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init]
 [dictionary setObject:@"notification" forKey:@"action"];

    [MainInterfaceController openParentApplication:dictionary reply:^(NSDictionary *replyInfo, NSError *error) {
//handle the reply if you want to... 
}
}

然后在AppDelegate中:

    - (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
        {
  if([[userInfo objectForKey:@"action"] isEqualToString:@"notification"] ){

        //fire the notification 
         UILocalNotification* localNotification = [[UILocalNotification alloc] init];
            localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:3];
            localNotification.alertBody = @"Your alert message";
            localNotification.timeZone = [NSTimeZone defaultTimeZone];
            [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

// you can use Reply(Dictinary); for responding to watchKit extention OK or KO...
        }

不要忘记在appDelegate中要求获得通知的许可:

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


    UIUserNotificationType types = UIUserNotificationTypeBadge |
    UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

    UIUserNotificationSettings *mySettings =
    [UIUserNotificationSettings settingsForTypes:types categories:nil];

    [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

    return YES;
}