是否可以从其他IntefaceController调用扩展委托中的方法?
类似的东西:
InterfaceController *interfaceController =[[InterfaceController alloc] init];
interfaceController callMethod
我的界面控制器
#import "InterfaceController.h"
#import "OrdinaryEventRow.h"
#import <UIKit/UIKit.h>
#import <WatchConnectivity/WatchConnectivity.h>
@interface InterfaceController()
@implementation InterfaceController
- (void)awakeWithContext:(id)context {
[super awakeWithContext:context];
//Configure interface objects here.
-(void)doSomething {
[self presentControllerWithName:@"goalView" context:nil];
}
@end
ExtensionDelegate:
#import "ExtensionDelegate.h"
#import "InterfaceController.h"
#import <WatchConnectivity/WatchConnectivity.h>
#import "setGoal.h"
@implementation ExtensionDelegate
//Handle Local Notification Actions
-(void)handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UNNotification *)localNotification{
if([identifier isEqualToString:@"action"]){
//Setup WCSession
if ([WCSession isSupported]) {
[[WCSession defaultSession] setDelegate:self];
[[WCSession defaultSession] activateSession];
//Get the value from slider
NSString *someString = [[NSUserDefaults standardUserDefaults]
stringForKey:@"Update"];
NSString *Update = @"Update";
NSDictionary *applicationData = [[NSDictionary alloc] initWithObjects:@[Update] forKeys:@[@"Update"]];
//Send Message to the iPhone (handle over the goal value)
[[WCSession defaultSession] sendMessage:applicationData
replyHandler:^(NSDictionary *reply) {
//handle reply from iPhone app here
}
errorHandler:^(NSError *error) {
//catch any errors here
}
];
}
}
//If Goal Setting was clicked
if([identifier isEqualToString:@"action3"]){
//here I want to call doSomething from InterfaceController
}
}
所以我只想从ExtensionDelegate调用InterfaceController中定义的方法。
答案 0 :(得分:1)
无法从WKInterfaceController
初始化ExtensionDelegate
并在其上调用方法。如果您尝试调用方法的控制器是根控制器,则可以从rootController
投射它的WKExtension
获取ExtensionDelegate
并在其上调用方法。
// Objective-C
if ([WKExtension shared].rootController isKindOfClass:[InitialInterfaceController class]) {
(InitialInterfaceController *)[WKExtension shared].rootController customMethod];
}
// Swift
if let root = WKExtension.shared().rootInterfaceController as? InitialInterfaceController {
root.customMethod()
}
*我的Objective-c有点生疏,所以如果有语法错误,请在评论中更新或告诉我,我可以编辑。
从您的代码示例中,您尝试基于本地通知执行操作,因此最好的办法是在接口控制器本身中处理通知。取决于您正在使用的watchOS
watchOS 3
handleAction(withIdentifier:for:) reference
watchOS 2
handleAction(withIdentifier:for:) reference
这里重要的注意事项是,这些方法被称为扩展委托不会实现handleAction(withIdentifier:for :)方法,WatchKit会在应用程序的根接口控制器上调用此方法来响应通知界面中的按钮点击。