ios - 我们可以打开 watch 扩展上的联系人吗

标签 ios watchkit apple-watch

如何在 watch 扩展中以编程方式打开 iPhone 的联系人,就像我们在 iOS 中使用地址簿一样。

提前致谢

最佳答案

通常从您使用的 WatchKit 扩展与 iPhone 通信

+ (BOOL)openParentApplication:(NSDictionary *)userInfo reply:(void(^)(NSDictionary *replyInfo, NSError *error)) reply;    // launches containing iOS application on the phone. userInfo must be non-nil
WKInterfaceController的方法类(class)。

因此,例如,您可以将 Storyboard中按钮的 IBAction 附加到此方法
- (IBAction)callPhoneAppButtonTapped
{
    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"text to display on iPhone", @"key", nil];

    [InterfaceController openParentApplication:dictionary reply:^(NSDictionary *replyInfo, NSError *error) {
        NSLog(@"Reply received by Watch app: %@", replyInfo);
    }];
}

注:为了从通讯簿中获取数据,用户需要授予您的应用权限。但应用程序将在后台启动,用户将专注于 Watch,因此最好在您的 iPhone 应用程序中请求此权限。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
        ABAddressBookRequestAccessWithCompletion(ABAddressBookCreateWithOptions(NULL,  nil), ^(bool granted, CFErrorRef error) {
    if (!granted){
        NSLog(@"Access denied");
        return;
    }
    NSLog(@"Access granted");
});
}

为了处理 openParentApplication:reply 发送的消息在您的 AppDelegate 实现中
- (void)application:(UIApplication *)application handleWatchKitExtensionRequest:(NSDictionary *)userInfo reply:(void (^)(NSDictionary *))reply
{
    NSLog(@"Request received by iOS app");
    NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"your value to return to Apple Watch", @"key", nil];

    // Here your app will be launch in background. Fetch AddressBook or other data you need.
    // Remember to call reply block in the end.  

    // Example of saving data to Address Book
    NSString *firstName;
    NSString *lastName;

    firstName = @"Maggie";
    lastName = @"Peggie";

    ABAddressBookRef addressBookRef = ABAddressBookCreateWithOptions(NULL, nil);
    ABRecordRef contact = ABPersonCreate();

    ABRecordSetValue(contact, kABPersonFirstNameProperty, (__bridge CFStringRef) firstName, nil);
    ABRecordSetValue(contact, kABPersonLastNameProperty, (__bridge CFStringRef)lastName, nil);

    ABAddressBookAddRecord(addressBookRef, contact, nil);
    ABAddressBookSave(addressBookRef, nil);

    reply(dictionary);
}

关于ios - 我们可以打开 watch 扩展上的联系人吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27961843/

相关文章:

iphone - 如何使用 Coredata 添加和使用现有的 SQLite 数据库(x.db)?

ios - 如何使用 WatchKit 创建圆形图像?

ios - Swift 中 NSLayoutContraint 的简单用法?

ios - 如何在 WatchKit 应用程序中正确测试通知?

watchkit - 从另一个 watch 套件应用程序中启动 watch 套件应用程序

ios - Watch App : [WCSession defaultSession]. isReachable 总是在后台应用程序上检索 'FALSE' 状态?

ios - 如何使用界面生成器重叠 iOS watch 套件中的两个控件

swift 3 : Watch app: if watch goes to sleep there's a delay between interface controllers

iphone - iOS - 设置锁屏图像

iPhone:将 FPPopover 类与 UIBarButtonItem 一起使用时出错