iOS由于沙盒的存在,應(yīng)用程序不能越過(guò)自己的區(qū)域去訪問(wèn)別的存儲(chǔ)空間的內(nèi)容,不過(guò)可能有許多場(chǎng)景我們需要在應(yīng)用程序之間共享數(shù)據(jù),比如多個(gè)應(yīng)用共用用戶名密碼進(jìn)行登錄等。
1、UIPasteboard
剪貼板是應(yīng)用程序之間傳遞數(shù)據(jù)的簡(jiǎn)單方式,建議不要使用全局的粘貼板,而是自己根據(jù)名字創(chuàng)建一個(gè)新的粘貼板,防止其它地方全局拷貝的影響。然后把需要共享的內(nèi)容復(fù)制到粘貼板,粘貼板的內(nèi)容可以是文本、URL、圖片和UIColor等,另一個(gè)app就可以根據(jù)粘貼板的名字去讀取相關(guān)的信息。
設(shè)置粘貼板的內(nèi)容:
UIPasteboard *pasteboard = [UIPasteboard pasteboardWithName:@"myPasteboard" create:YES];
pasteboard.string = @"myShareData";
讀取粘貼板的內(nèi)容:
UIPasteboard *pasteboard = [UIPasteboard pasteboardWithName:@"myPasteboard" create:NO]; NSString *content = pasteboard.string;
2、Custom URL Scheme
NSURL *myURL = [NSURL URLWithString:@"todolist://newid=20"];
[[UIApplication sharedApplication] openURL:myURL];
3、Shared Keychain Access
保存數(shù)據(jù)到keychain(為了簡(jiǎn)單使用SSKeychian)
- (void)setKeyChain
{
[SSKeychain setPassword:@"shareData" forService:@"myservice" account:@"jiangbin"];
}
讀取數(shù)據(jù)
- (IBAction)getByKeychain:(id)sender
{
NSString *myData = [SSKeychain passwordForService:@"myservice" account:@"jiangbin"];
}
4、App Groups
iOS8之后蘋果加入了App Groups功能,應(yīng)用程序之間可以通過(guò)同一個(gè)group來(lái)共享資源,app group可以通過(guò)NSUserDefaults進(jìn)行小量數(shù)據(jù)的共享,如果需要共享較大的文件可以通過(guò)NSFileCoordinator、NSFilePresenter等方式。
根據(jù)group name設(shè)置內(nèi)容:
- (void)setAppGroup
{
NSUserDefaults *myDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.jiangbin.SharedData"];
[myDefaults setObject:@"shared data" forKey:@"mykey"];
}
根據(jù)group name讀取數(shù)據(jù)
- (void)getByAppGroup
{
NSUserDefaults *myDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.jiangbin.SharedData"];
NSString *content = [myDefaults objectForKey:@"mykey"];
}