iCloud的苹果推出的一套云服务系统,他的主要作用是为了能让苹果的各个类型的设备以及不同的app之间能实现数据共享。我最近做的一个项目就使用到了这个功能,本人从事蓝牙开发,现在公司的固件更新了,推出了新的app,但是,如果用户同时安装了新的app和之前的app就需要这两个app之间能共享数据。下面是我学习icloud的一些简单笔记:
1.要使用iCloud功能,必须在项目中打开iCloud,TARGETS---->Capabilities-->iCloud,如果你的程序需要真机测试和发布的,你还要在创建的证书中让它支持iCloud
2.下面是参考的简单代码:
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
/**
* 文件的读写
*
*/
-(void)fileReadAndWrite{
NSFileManager *manager=[NSFileManager defaultManager];
NSURL *fileUrl=[manager URLForUbiquityContainerIdentifier:@"icloud"];
fileUrl=[fileUrl URLByAppendingPathComponent:@"Documents"];
//判断此路径是否存在
if ([manager fileExistsAtPath:[fileUrl path]]) {
//存在
}else{
//不存在---->重新创建
[manager createDirectoryAtURL:fileUrl withIntermediateDirectories:YES attributes:[NSDictionary dictionaryWithObject:@"Vincent" forKey:@"name"] error:nil];
}
fileUrl=[fileUrl URLByAppendingPathComponent:@"myInfo.txt"];
//写入数据
[@"好好学习,天天向上" writeToURL:fileUrl atomically:YES encoding:NSUTF8StringEncoding error:nil];
//读取数据
NSString *icloudStr=[[NSString alloc]initWithContentsOfURL:fileUrl encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",icloudStr);
}
/**
* key-Value的读写
*
*/
-(void)keyAndValue{
//先取得icloud的token
NSUbiquitousKeyValueStore *myStore=[[NSUbiquitousKeyValueStore alloc]init];
//写入数据
[myStore setValue:@"Vincent" forKey:@"name"];
//在icloud的key-value操作数据之后必须在icloud同步
[myStore synchronize];
//读取数据
NSLog(@"%@",[myStore valueForKey:@"name"]);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
//不管哪种读写方式,都需要先判断app是否支持iCloud服务
NSFileManager *manager=[NSFileManager defaultManager];
id token=[manager ubiquityIdentityToken];
if (token) {
//支持
int i=arc4random()%2;
switch (i) {
case 0:
//文件读写方式
[self fileReadAndWrite];
break;
case 1:
//key-Value方式
[self keyAndValue];
break;
default:
break;
}
}else{
//不支持
}
return YES;
}