iCloud的使用

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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值