• ios sinaweibo 客户端(三)


    这个页面要讲述的是用户的粉丝列表,下面是效果图:

     

    可以看到这个视图明显也是一个tableview,在每一个cell中包含的有三个部分的内容:粉丝头像image,粉丝昵称label,我和粉丝之间的相互关注情况button。

    在这个页面我们主要处理的内容有:① 粉丝列表数据的获取  ②tableview视图界面的组织(重点是:添加关注和取消关注)

    (1)首先是获取粉丝列表数据,这部分内容没有什么好说的,就是些JSON数据,然后解析。调用的API:https://api.weibo.com/2/friendships/followers.json。其中有一个点是需要注意的。我们注意到其中API请求的参数:

     

    count false int 单页返回的记录条数,默认为50,最大不超过200。
    cursor false int 返回结果的游标,下一页用返回值里的next_cursor,上一页用previous_cursor,默认为0。

     

    可以知道一次数据请求是以页的方式返回的,每一页返回count条数的粉丝记录,这个和前面微博内容的返回的差不多的,都是以页为单位返回,但是这里有一个比较特殊的是,在这个API的数据请求中没有page这个参数,而是用到了cursor这个参数,这个参数开始是0,以后每一次请求后获取的数据中就有next_cursor这个返回值,用它来为cursor赋值,就可以继续获取接下去的数据了,如果粉丝数据已经全部获取到了,那么这个值返回就又是0了。那么我们在继续加载的时候就可以添加一个判断,判断next_cursor是否为0,如果不为0,说明粉丝列表还没有加载完毕,可以继续请求加载;如果为0,则说明所有的粉丝数据都已经加载了,这时就不要继续再加载了。

     

    下面通过代码看看吧!

     

    1. - (void) loadFollersDataWithCursor:(int) cursor {  
    2.       
    3.     dispatch_async(dispatch_get_global_queue(0, 0), ^{  
    4.           
    5.         dispatch_sync(dispatch_get_global_queue(0, 0), ^{  
    6.               
    7.             hud = [[MBProgressHUD alloc] init];  
    8.             hud.dimBackground = YES;  
    9.             hud.labelText = @"正在加载数据...";  
    10.             [hud show:YES];  
    11.             [self.view addSubview:hud];  
    12.               
    13.             //同步GET请求粉丝数据  
    14.             NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[InfoForSina returnFollowersUrlStringWithCursor:cursor]]];  
    15.             NSError *error;  
    16.             NSData *followersData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];  
    17.               
    18.             //使用JSONKit解析数据  
    19.             NSString *follwersString = [[NSString alloc] initWithData:followersData encoding:NSUTF8StringEncoding];  
    20.               
    21.             NSDictionary *followersDictionary = [follwersString objectFromJSONString];  
    22.             NSArray *followersArray = [followersDictionary objectForKey:@"users"];  
    23.               
    24.             followersCount = [[followersDictionary objectForKey:@"total_number"] integerValue]; //粉丝总数  
    25.             nextCursor = [[followersDictionary objectForKey:@"next_cursor"] integerValue];  //粉丝列表  
    26.               
    27.             for (NSDictionary *dictionary in followersArray) {  
    28.                   
    29.                 User *followersUser = [[User alloc] init];  
    30.                 [followersUser initUserWithDictionary:dictionary];  
    31.                 [self.followersMutableArray addObject:followersUser];  
    32.                   
    33.             }  
    34.               
    35.         });  
    36.         dispatch_sync(dispatch_get_main_queue(), ^{  
    37.               
    38.             [self.tableView reloadData];  
    39.             [hud removeFromSuperview];  
    40.         });  
    41.           
    42.     });  
    43. }  
    44.   
    45. //处理tableview滑动到底了  
    46. - (void) scrollViewDidScroll:(UIScrollView *)scrollView {  
    47.       
    48.     CGPoint contentOffsetPoint = self.tableView.contentOffset;  
    49.       
    50.     CGRect frame = self.tableView.frame;  
    51.       
    52.     if (contentOffsetPoint.y == self.tableView.contentSize.height - frame.size.height)  
    53.     {  
    54.         if (nextCursor!=0) {  
    55.             [self loadFollersDataWithCursor:nextCursor];  
    56.         }  
    57.         //全部加载完毕  
    58.         else {  
    59.             MBProgressHUD *endHud = [[MBProgressHUD alloc] init];  
    60.             endHud.mode = MBProgressHUDModeText;  
    61.             endHud.labelText = @"提示";  
    62.             endHud.detailsLabelText = @"粉丝数据已全部加载!";  
    63.             [self.tableView addSubview:endHud];  
    64.             [endHud show:YES];  
    65.             [endHud hide:YES afterDelay:0.5];  
    66.         }  
    67.   
    68.     }  
    69. }  


    注意到其中的nextCursor这个参数,就是用来继续加载的关键参数,在开始的时候

     

    nextCursor = 0;
    [self loadFollersDataWithCursor:nextCursor]; 

    以后每一次加载数据的时候就用获取到的新值为它重新赋值。

    (2)tableview视图界面的组织

    这里粉丝头像和粉丝的昵称的显示就不多说了,很简单的。代码如下:

     

    1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
    2. {  
    3.     static NSString *CellIdentifier = @"FansCell";  
    4.     FansCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];  
    5.     if (cell == nil) {  
    6.         cell = [[FansCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];  
    7.     }  
    8.       
    9.     //这里的User类就是表示一个粉丝  
    10.     User *aUser = [[User alloc] init];  
    11.     aUser = [_followersMutableArray objectAtIndex:[indexPath row]];  
    12.       
    13.     cell.nameLabel.adjustsFontSizeToFitWidth = YES;  
    14.     cell.nameLabel.text = aUser.nameString;  
    15.       
    16.     //设置按键文字  
    17.     cell.fansButtonLabel.titleLabel.adjustsFontSizeToFitWidth = YES;  
    18.     if (aUser.following) {  
    19.         //表示我已经关注了该粉丝  
    20.         [cell.fansButtonLabel setTitle:@"互相关注" forState:UIControlStateNormal];  
    21.     }  
    22.     else {  
    23.         [cell.fansButtonLabel setTitle:@"+关注" forState:UIControlStateNormal];  
    24.     }  
    25.       
    26.     //设置头像  
    27.         __block NSData *imageData;  
    28.         dispatch_async(dispatch_get_global_queue(0, 0), ^{  
    29.               
    30.             dispatch_sync(dispatch_get_global_queue(0, 0), ^{  
    31.                 imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:aUser.profileImageURL]];  
    32.             });  
    33.                           
    34.             dispatch_sync(dispatch_get_main_queue(), ^{  
    35.                 UIImage *image = [[UIImage alloc] initWithData:imageData];  
    36.                 [cell.imageView setImage:image];  
    37.             });  
    38.         });  
    39.       
    40.     //头像设置圆角  
    41.     CALayer *l = [cell.imageView layer];   //获取ImageView的层  
    42.     [l setMasksToBounds:YES];  
    43.     [l setCornerRadius:6.0];  
    44.       
    45.     //设置粉丝的id号,这里只是为取消关注或者添加关注的请求参数用  
    46.     cell.fansUIDString = aUser.IDString;  
    47.       
    48.     return cell;  
    49. }  


    说明:

     

    1、里面的头像我设置成圆角,这时需要#import "QuartzCore/QuartzCore.h",其他都可以看懂的吧。

    2、其中获取头像的方法是:

     

    1. -(UIImage *) getImageFromURL:(NSString *)fileURL {  
    2.     UIImage * resultImage = [[UIImage alloc] init];  
    3.     NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];  
    4.     resultImage = [UIImage imageWithData:data];  
    5.     return resultImage;  
    6. }  

     

     

       在这一部分的内容中要值得说明的是我添加的那个按键的处理。首先说一下我这个按键的作用:我们在获取到的粉丝JSON数据中有:follow_me和following这两个项,前者表示的是该粉丝是否关注我,显然我的粉丝肯定是关注我的啦,所以一直返回是true;后者表示的是我是否关注这个粉丝,有关注返回true,否则就返回false。所以我们就可以在这里面做点事情了。

     

    如果我没有关注这个粉丝即following是false的话,button的作用就是可以添加对这个粉丝的关注,button的label就是“+关注”。

    如果我关注了这个粉丝即following是true的话,button的作用就是可以取消对这个粉丝的关注,button的label就是“取消关注”;

    由于有这部分的处理,所以我定义了一个Fanscell类专门是用于处理cell这部分的内容。

    下面着重讲的是关注和取消关注粉丝的处理。

    ①、请求API及参数

     添加关注的API:https://api.weibo.com/2/friendships/create.json

    取消关注的API: https://api.weibo.com/2/friendships/destroy.json

    二者调用时所需的参数除了access_token之外,还要粉丝的uid或者screen_name(二选一),注意前者是long long (int64)类型,后者是string类型,我选用的是uid这个参数。

    ②、Fanscell类

    其中包括的有:

     

    1. - (IBAction)fansButton:(id)sender;  
    2. @property (weak, nonatomic) IBOutlet UIButton *fansButtonLabel;  
    3. @property (weak, nonatomic) IBOutlet UILabel *nameLabel;  
    4. @property (weak, nonatomic) IBOutlet UIImageView *headImageView;  
    5. @property (strong, nonatomic) NSString *fansUIDString;//粉丝的UID  

     

    其中的fansButton方法是用来处理关注和取消关注粉丝的。

    下面先给出处理的过程代码再解说:

     

    1. - (IBAction)fansButton:(id)sender {  
    2.       
    3.     destroyFriendships = NO;  
    4.     creatFriendships = NO;  
    5.       
    6.     if ([self.fansButtonLabel.titleLabel.text isEqualToString:@"互相关注"]) {  
    7.           
    8.         destroyFriendships = YES;  
    9.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否取消关注" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];  
    10.         [alert show];  
    11.     }  
    12.   
    13.     else if ([self.fansButtonLabel.titleLabel.text isEqualToString:@"+关注"]) {  
    14.         creatFriendships = YES;  
    15.         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否关注" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];  
    16.         [alert show];  
    17.     }  
    18.   
    19. }  
    20. - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {  
    21.     //取消关注  
    22.     if (destroyFriendships && buttonIndex == 1) {  
    23.   
    24.         MBProgressHUD *custuonHUD = [[MBProgressHUD alloc]init];  
    25.         custuonHUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]];  
    26.         custuonHUD.mode = MBProgressHUDModeCustomView;  
    27.         [self addSubview:custuonHUD];  
    28.           
    29.         NSURL *url = [NSURL URLWithString:FRIENDSHIPS_DESTROY];  
    30.         ASIFormDataRequest *item = [[ASIFormDataRequest alloc] initWithURL:url];  
    31.         [item setPostValue:[InfoForSina returnAccessTokenString]    forKey:@"access_token"];  
    32.         [item setPostValue:[NSString stringWithFormat:@"%lld",[_fansUIDString longLongValue]]  forKey:@"uid"];  
    33.         [item setCompletionBlock:^{  
    34.               
    35.             [self.fansButtonLabel setTitle:@"+关注" forState:UIControlStateNormal];  
    36.               
    37.             custuonHUD.labelText = @"取消关注成功!";  
    38.             [custuonHUD show:YES];  
    39.             [custuonHUD hide:YES afterDelay:2];  
    40.   
    41.         }];  
    42.         [item setFailedBlock:^{  
    43.               
    44.             custuonHUD.labelText = @"取消关注失败!";  
    45.             [custuonHUD show:YES];  
    46.             [custuonHUD hide:YES afterDelay:2];  
    47.   
    48.         }];  
    49.         [item startAsynchronous];  
    50.           
    51.           
    52.     }  
    53.     //添加关注  
    54.     else if (creatFriendships && buttonIndex == 1) {  
    55.         //使用ASI这个类库处理添加关注的数据请求  
    56.         /* 
    57.         MBProgressHUD *custuonHUD = [[MBProgressHUD alloc]init]; 
    58.         custuonHUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]]; 
    59.         custuonHUD.mode = MBProgressHUDModeCustomView; 
    60.         [self addSubview:custuonHUD]; 
    61.         
    62.          
    63.         NSURL *url = [NSURL URLWithString:FRIENDSHIPS_CREAT]; 
    64.         ASIFormDataRequest *item = [[ASIFormDataRequest alloc] initWithURL:url]; 
    65.         [item setPostValue:[InfoForSina returnAccessTokenString]    forKey:@"access_token"]; 
    66.         [item setPostValue:[NSString stringWithFormat:@"%lld",[_fansUIDString longLongValue]]  forKey:@"uid"]; 
    67.         [item setCompletionBlock:^{ 
    68.              
    69.             [self.fansButtonLabel setTitle:@"互相关注" forState:UIControlStateNormal]; 
    70.             custuonHUD.labelText = @"关注成功!"; 
    71.             [custuonHUD show:YES]; 
    72.             [custuonHUD hide:YES afterDelay:1]; 
    73.              
    74.         }]; 
    75.         [item setFailedBlock:^{ 
    76.             custuonHUD.labelText = @"关注失败!"; 
    77.             [custuonHUD show:YES]; 
    78.             [custuonHUD hide:YES afterDelay:1]; 
    79.  
    80.         }]; 
    81.         [item startAsynchronous]; 
    82.         */  
    83.           
    84.         //不使用ASI这个类库处理添加关注的数据请求  
    85.         NSURL *url = [NSURL URLWithString:FRIENDSHIPS_CREAT];  
    86.         NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5.0];  
    87.         [request setHTTPMethod:@"POST"];  
    88.         NSString *postString = [NSString stringWithFormat:@"access_token=%@&uid=%lld",[InfoForSina returnAccessTokenString],[_fansUIDString longLongValue]];  
    89.         NSMutableData *postData = [[NSMutableData alloc] init];  
    90.         [postData appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]];  
    91.         [request setHTTPBody:postData];  
    92.         self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];  
    93.     }  
    94. }  
    95.   
    96. #pragma mark - NSURLConnection delegate Methods  
    97.   
    98. -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response  
    99. {  
    100.     self.responseData = [[NSMutableData alloc] initWithLength:0];  
    101. }  
    102.   
    103. -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data  
    104. {  
    105.     [self.responseData appendData:data];  
    106. }  
    107.   
    108. -(void)connectionDidFinishLoading:(NSURLConnection *)theconnection  
    109. {  
    110.     MBProgressHUD *custuonHUD = [[MBProgressHUD alloc]init];  
    111.     custuonHUD.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]];  
    112.     custuonHUD.mode = MBProgressHUDModeCustomView;  
    113.     [self addSubview:custuonHUD];  
    114.       
    115.     NSError *error;  
    116.     NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:&error];  
    117.       
    118.     NSString *idString = [dict objectForKey:@"idstr"];  
    119.     if(idString) {  
    120.         [self.fansButtonLabel setTitle:@"互相关注" forState:UIControlStateNormal];  
    121.         custuonHUD.labelText = @"关注成功!";  
    122.         [custuonHUD show:YES];  
    123.         [custuonHUD hide:YES afterDelay:2.3];  
    124.     }  
    125.     else {  
    126.         custuonHUD.labelText = @"关注失败!";  
    127.         [custuonHUD show:YES];  
    128.         [custuonHUD hide:YES afterDelay:2.3];  
    129.     }  
    130.       
    131.     [self.connection cancel];  
    132. }  
    133.   
    134. -(void)connection:(NSURLConnection *)theconnection didFailWithError:(NSError *)error  
    135. {  
    136.     MBProgressHUD *failedHud = [[MBProgressHUD alloc] init];  
    137.     failedHud.mode = MBProgressHUDModeText;  
    138.     failedHud.labelText = @"提示";  
    139.     failedHud.detailsLabelText = @"发表评论失败!";  
    140.     [failedHud show:YES];  
    141.     [self addSubview:failedHud];  
    142.     [failedHud hide:YES afterDelay:1.3];  
    143.     [self.connection cancel];  
    144. }  


    说明:

     

    1、当按下这个button时会触发一个UIAlertView,提示是否确定关注和取消关注。

              

    2、确定要关注或者取消关注粉丝的处理在UIAlertView的delegate方法中处理。

    3、关注和取消关注粉丝的数据请求方式是POST,我们可以用ASIHTTPRequest来异步方式处理,也可以用不用这个类库,用系统自带的方法异步POST处理。代码中有我使用了这这两种方式。其中取消关注我是使用ASIHTTPRequest,而添加关注是使用系统自带的方法(当然注释部分也给出了ASIHTTPRequest的使用代码)。

    注意,如果是使用系统自带的方式异步POST处理,我还添加了两个property:

    @property (strong, nonatomic) NSURLConnection *connection;
    @property (strong, nonatomic) NSMutableData *responseData;

    通过代码可以清楚的看到,前一种处理方式十分简洁,后一种处理方式由于要实现delegate方法,所以感觉有点麻烦,二者孰好孰不好,自己感觉咯!

    4、在数据请求结束我继续使用MBProgressHUD这个类库添加了一些提示框,表示关注是否成功或者取消关注是否成功。效果如下:

              

     

    这个页面的处理差不多就是这样了!微笑

  • 相关阅读:
    Cmder配置
    uboot移植
    嵌入式产品开发技术问题
    flexbox布局
    使用PS过程
    STM32 使用 FreeRTOS过程记录
    TTL、RS232、RS485、串口
    用纯css改变下拉列表select框的默认样式
    task9暂存
    Hello World
  • 原文地址:https://www.cnblogs.com/yulang314/p/3549550.html
Copyright © 2020-2023  润新知