Share between an iOS extension and its containing app with the keychain?

后端 未结 4 1467
渐次进展
渐次进展 2021-02-07 03:43

I understand I can share data between my share extension and its containing app by enabling app groups and using NSUserDefaults (see Sharing data between an iOS 8 share extensio

4条回答
  •  甜味超标
    2021-02-07 04:14

    Using the standard Objective-C KeychainItemWrapper class and with an entry of #import "KeychainItemWrapper.h" in the bridging header:

        func btnSaveAction() {
    
        let appGroupID = "group.com.yourcompany.appid"
        let keychain = KeychainItemWrapper(identifier: "Password", accessGroup:appGroupID)
        keychain.setObject(self.txtfldPassword.text!, forKey:kSecValueData)
        keychain.setObject(self.txtfldEmail.text!, forKey:kSecAttrAccount)
    
        }
    

    On the Watch extension side (Swift):

    override func awakeWithContext(context: AnyObject?) {
        super.awakeWithContext(context)
    
        let appGroupID = "group.com.yourcompany.appid"
        let keychain = KeychainItemWrapper(identifier: "Password", accessGroup:appGroupID)
        println(keychain.objectForKey(kSecAttrAccount))
        println(keychain.objectForKey(kSecValueData))
    
    }
    

    In Objective C, watchkit extension:

    NSString *appGroupID = @"group.com.yourcompany.appid";
    KeychainItemWrapper *keychain = [[KeychainItemWrapper alloc] initWithIdentifier:@"Password" accessGroup:appGroupID];
    [keychain setObject:(__bridge id)(kSecAttrAccessibleWhenUnlocked) forKey:(__bridge id)(kSecAttrAccessible)];
    NSLog(@"account = %@", [keychain objectForKey:(__bridge id)(kSecAttrAccount)]);
    NSLog(@"password =%@", [keychain objectForKey:(__bridge id)(kSecValueData)]);
    

    Don't forget to turn on "Keychain Sharing" under "Capabilities" for both the phone app and watch kit extension for same keychain group: "group.com.yourcompany.appid"

提交回复
热议问题