技术文章分类(180)

技术随笔(11)

Parse的使用(ios程序员必须熟练掌握,我是相见很晚呀)

demo下载:https://github.com/MartinLi841538513/ParseDemo

先简单简介:Parse相当于你有了自己的后台和服务器。其好处将不言而喻。

功能:

1:自定义数据字典

2:消息推送

3:地理位置

4:数据缓存

5:离线数据同步

6:云端自定义代码

7:二进制文件读取

 

使用操作:

一,登陆www.parse.com注册一个账号,并创建一个app,记录applicationId和clientKey(后面会用到)

二,引入Parse库,据说还要引入Facebook-iOS-SDK库。如果使用pods管理库,那么只需配置Parse,Facebook-iOS-SDK将会自动下载。

三,建议在程序运行时didFinishLaunchingWithOptions时候配置parse

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [Parse setApplicationId:@"5x5vbjHWFClYokC1N9s9D8iiPnKbRaR3w55WdUz8"
                  clientKey:@"kHfr4w7wKPKCDR7hOREtNKxE3MeJyRiNuHTlvmdf"];
       return YES;
}

四,这里的demo将实现以下几个功能:

1,存,取数据

2,注册,登陆User

3,上传,下载image

下面我将按顺序实现上面6个功能:

- (IBAction)save:(id)sender {
    
    PFObject *anotherPlayer = [PFObject objectWithClassName:@"Player"];
    [anotherPlayer setObject:@"Jack" forKey:@"Name"];
    [anotherPlayer setObject:[NSNumber numberWithInt:840] forKey:@"Score"];
    [anotherPlayer saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (succeeded){
            NSLog(@"Object Uploaded!");
        }
        else{
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            NSLog(@"Error: %@", errorString);
        }
        
    }];


}
- (IBAction)query:(id)sender {
    
    PFQuery *query = [PFQuery queryWithClassName:@"Player"]; //1
    [query whereKey:@"Name" equalTo:@"Jack"];//2
    [query whereKey:@"Score" greaterThan:[NSNumber numberWithInt:100]]; //3
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {//4
        if (!error) {
            NSLog(@"Successfully retrieved: %@", objects);
        } else {
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            NSLog(@"Error: %@", errorString);
        }
    }];
}
- (IBAction)signIn:(id)sender {
    [PFUser logInWithUsernameInBackground:@"MartinLi" password:@"123456" block:^(PFUser *user, NSError *error) {
        if (user) {
            //Open the wall
            NSLog(@"sign in successful");
        } else {
            //Something bad has ocurred
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [errorAlertView show];
        }
    }];
}
- (IBAction)signUp:(id)sender {
    //1
    PFUser *user = [PFUser user];
    //2
    user.username = @"MartinLi";
    user.password = @"123456";
    user.email = @"841538513@qq.com";
    //3
    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (!error) {
            //The registration was successful, go to the wall
            NSLog(@"sign up successful");
        } else {
            //Something bad has occurred
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [errorAlertView show];
        }
    }];
}
- (IBAction)imageUpload:(id)sender {
    //Upload a new picture
    //1
    PFFile *file = [PFFile fileWithName:@"img" data:UIImagePNGRepresentation([UIImage imageNamed:@"QRCodeImage"])];
    [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        if (succeeded){
            //2
            //Add the image to the object, and add the comment and the user
            PFObject *imageObject = [PFObject objectWithClassName:@"ImageObject"];
            [imageObject setObject:file forKey:@"image"];
            [imageObject setObject:[PFUser currentUser].username forKey:@"user"];
            [imageObject setObject:@"我的头像" forKey:@"comment"];
            //3
            [imageObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                //4
                if (succeeded){
                    //Go back to the wall
                    [self.navigationController popViewControllerAnimated:YES];
                }
                else{
                    NSString *errorString = [[error userInfo] objectForKey:@"error"];
                    UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                    [errorAlertView show];
                }
            }];
        }
        else{
            //5
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [errorAlertView show];
        }
    } progressBlock:^(int percentDone) {
        NSLog(@"Uploaded: %d %%", percentDone);  
    }];
}
- (IBAction)showImage:(id)sender {
    //Prepare the query to get all the images in descending order
    //1
    PFQuery *query = [PFQuery queryWithClassName:@"ImageObject"];
    //2
    [query orderByDescending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        //3
        if (!error) {
            //Everything was correct, put the new objects and load the wall
            PFObject *imageObject = [objects firstObject];
            PFFile *imageFile = (PFFile *)[imageObject objectForKey:@"image"];
            UIImage *image = [UIImage imageWithData:imageFile.getData];
            imgView.image = image;
            
        } else {
            
            //4
            NSString *errorString = [[error userInfo] objectForKey:@"error"];
            UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [errorAlertView show];
        }
    }];
}

 

下面我将详细介绍Parse:

什么是Parse?
Parse是一群美国人开发的专为移动APP服务的云计算平台,与现有的其他云计算平台相比,Parse除了提供Restful的service 之外,也提供了官方的iOS和Android SDK。个人认为高质量的client端SDK是Parse区分与其他云服务的核心优势。为什么呢?看完我的文章就知道了。

为什么要用Parse?
先想想开发一个简单的需要保存用户数据的APP,你需要做什么。非技术背景的人多半会认为只需要找个人做几个手机界面就行了。慢!身为程序员的我们会告诉这个不懂技术的朋友(也许是投资人,也许是你的老板),为了保存用户数据及密码,我们需要建立一个数据库,建立一个服务器,找一个虚拟主机提供商部署服务,花费几天到几个月的时间开发服务器的代码,尽管这些事情看上去与一个运行在手机上的程序毫无关系,却是必须而不可或缺的。这些与iPhone开发无关的前期准备工作阻止了大多数个人或者小团体的创业想法变成实际行动。这时候,小团队的拯救者Parse出现了。只需专著于iPhone上具体需求的开发,繁琐的后台服务全由Parse包办。

Parse提供的服务?
多数功能免费,少数功能只开放给Pro用户(199$/month),具体情况可以访问官网(https://www.parse.com/plans)。

1. JASON格式的数据保存读取。可以理解为数据库+DAO+Service。No Schema,前台程序员无需预定义表结构,只要建立Object C 对象,保存时就可以自动建立对应面向对象的“数据库表”。传统开发过程中,整个后台服务的开发工作全部都省去了。

2. 用户管理。用户对象是最常用的,Parse提供了PFUser对象,包含了注册登陆重设密码等常用用户操作,并引入ACL管理对象的权限。

3. 消息推送:支持iOS和Android平台的消息推送。具体的说就是iOS开发者无须再建立自己的消息发送服务器了。

4. 文件存贮:除了类数据库的方式保存对象也支持二进制文件的保存。

5. 隐藏Parse: 默认情况,重设密码,验证油箱等功能使用带有Parse logo的网页和邮件地址。Pro用户可以自定义邮件模版,网页模版,或者要求Parse redirect到自己应用的官网。

6. Facebook和Twitter账户绑定。就是建立PFUser和Facebook和Twitter账户的关联。同时Parse的SDK也包含了Facebook和Twitter的SDK。这个应该只对那些面向国外市场的同学有用。


Parse的SDK包括什么?
第三方的云服务满天飞,好用才是关键。看看Parse团队的介绍,都是些牛人,放出来的SDK的质量也没话说。官方的有iOS和Android,非官方的基本都全了,包括WP,PHP,Flex Java等等。这里只谈iOS的SDK。除了基本的和后台Restful API的接口外,还包括了一个封装了下来刷新的table view controller,挺漂亮的登陆,注册界面,异步读取保存数据接口和Cache。官网上除了各种例子之外,最近还放出了个真正上App Store的项目AnyWall。有兴趣的同学可以去看看。

 

posted @ 2014-08-22 22:15  坤哥MartinLi  阅读(614)  评论(0编辑  收藏  举报