搜索
您的当前位置:首页正文

iOS 不同 App 数据共享

来源:二三娱乐

我们都知道,iOS 的 App 采用沙盒机制,使得不同的 App 在 iPhone 设备上保存的位置相互独立,从而保证 App 数据安全。沙盒机制只允许 App 访问自身数据,但是有时候,同样公司生产的 App 数据间有需要共享的需求:比如抖音 App 想要访问头条中的账号信息。苹果考虑到这种实际需求,通过 groups 和 keychain sharing 来具体实现。

同一开发者、不同 App 共享数据的 groups 通过 NSUserDefaults 来创建。[NSUserDefaults standardUserDefaults] 创建的 Group 只能访问本 App 沙数据。通过方法[[NSUserDefaults alloc] initWithSuiteName:@"xx"]可以创建用于 App 共享的容器。

下面介绍一下具体使用方式。
1 在 Xcode 中打开本工程 App Group 功能:


App Group.png

添加具体 group 名称, 保持以 group 开头。
2 添加具体使用代码:

#import "ViewController.h"

@interface ViewController ()

@property (weak, nonatomic) IBOutlet UITextField *pwdTF;

@property (nonatomic, strong) NSUserDefaults *groupDefault;

@property (nonatomic, copy) NSString *keyString;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.groupDefault = [[NSUserDefaults alloc] 
    self.keyString = 
}

- (IBAction)saveAction:(id)sender {
    
    NSString *pwdString = self.pwdTF.text;
    if (!pwdString.length) {
        [self showTipString:@"pwd can't be empty"];
        return;
    }
    
    [self.groupDefault setObject:pwdString forKey:self.keyString];
    [self showTipString:@"pwd save success"];
    
}

- (void)showTipString:(NSString *)tips{
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"Tips" message:tips preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"ok" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [alertC popoverPresentationController];
    }];
    [alertC addAction:action];
    [self presentViewController:alertC animated:true completion:nil];
    
}

- (IBAction)clearAction:(id)sender {
    
       self.pwdTF.text = nil;
    
}
- (IBAction)readAction:(id)sender {
    NSString *pwdString = [self.groupDefault objectForKey:self.keyString];
    self.pwdTF.text = pwdString;
    
}

3 另外一个项目中采用同样的上述设置。

通过 group 存储的数据,会随着 App 的全部删除而丢失。只要设备上存在一个账号下某一个 App ,那么共享 Group 中的数据就不会丢失。

底层的实现机理是 iOS 会将 group 和 keychain 展开成如下具体 ID:


 
 
喜欢和关注,都是对我的鼓励和支持~
Top