IOS Sina Weibo client demo practices (5) Fan list page

Source: Internet
Author: User

This page is about the user's fan list, which is as follows:


We can see that this view is obviously also a tableview. Each cell contains three parts: the fan profile image, the fan nickname label, and the mutual interest button between the fans and me.

On this page, we mainly deal with the following content: ① getting the data from the fans list ② organizing the tableview interface (Focus: adding and removing follow)

(1) first, retrieve the fan list data. There is nothing to say about this part, that is, some JSON data, and then parse it. Called API: https://api.weibo.com/2/friendships/followers.json. Note the following points. We noticed the parameters of the API request:

Count False Int Number of records returned on a single page. The default value is 50. The maximum value is 200.
Cursor False Int The cursor of the returned result. The next page uses next_cursor in the returned value, and the previous page uses previous_cursor. The default value is 0.

It can be seen that a data request is returned on a page, and each page returns a count of fans. This is similar to the one returned by the previous Weibo content, and is returned on a page, however, a special one here is that the "cursor" parameter is used instead of the "page" parameter in the data request of this API. This parameter starts with 0, the returned value next_cursor is included in the data obtained after each request. You can use it to assign values to the cursor to continue obtaining the next data. If all the fan data has been obtained, then the returned value is 0 again. Then, when loading continues, we can add a judgment to determine whether next_cursor is 0. If it is not 0, it indicates that the fans list has not been loaded, and we can continue to request loading; if the value is 0, it indicates that all the fan data has been loaded. In this case, do not continue loading.


The following code is used to check it out!

-(Void) loadfollersdatawithcursor :( INT) cursor {dispatch_async (dispatch_get_global_queue (0, 0), ^ {dispatch_sync (dispatch_get_global_queue (0, 0 ), ^ {HUD = [[mbprogresshud alloc] init]; HUD. dimbackground = yes; HUD. labeltext = @ "loading data... "; [HUD show: Yes]; [self. view addsubview: HUD]; // synchronize the GET request to the fan data nsurlrequest * request = [[nsurlrequest alloc] initwithurl: [nsurl urlwithstring: [infoforsina returnfol Lowersurlstringwithcursor: cursor]; nserror * error; nsdata * followersdata = [nsurlconnection sendsynchronousrequest: Request returningresponse: Nil error: & error]; // use jsonkit to parse data nsstring * follwersstring = [[nsstring alloc] initwithdata: followersdata encoding: encoding]; nsdictionary * encoding = [follwersstring encoding]; nsarray * followersarray = Ary objectforkey: @ "users"]; followerscount = [[followersdictionary objectforkey: @ "total_number"] integervalue]; // nextcursor = [[followersdictionary objectforkey: @ "next_cursor"] integervalue]; // fans list for (nsdictionary * dictionary in followersarray) {user * followersuser = [[user alloc] init]; [followersuser inituserwithdictionary: dictionary]; [self. followersmutablearray addobject: followersuse R] ;}}); dispatch_sync (dispatch_get_main_queue (), ^ {[self. tableview reloaddata]; [HUD removefromsuperview];}); // process the sliding of tableview to the end-(void) scrollviewdidscroll :( uiscrollview *) scrollview {cgpoint contentoffsetpoint = self. tableview. contentoffset; cgrect frame = self. tableview. frame; If (contentoffsetpoint. y = self. tableview. contentsize. height-frame. size. height) {If (nextcursor! = 0) {[self loadfollersdatawithcursor: nextcursor];} // All loaded else {mbprogresshud * endhud = [[mbprogresshud alloc] init]; endhud. mode = mbprogresshudmodetext; endhud. labeltext = @ "prompt"; endhud. detailslabeltext = @ "all fan data has been loaded! "; [Self. tableview addsubview: endhud]; [endhud show: Yes]; [endhud hide: Yes afterdelay: 0.5];}

Note that the nextcursor parameter is a key parameter used to continue loading.

Nextcursor = 0;
[Self loadfollersdatawithcursor: nextcursor];

In the future, each time the data is loaded, the new value is assigned to it again.

(2) Organization of the tableview Interface

The display of Fan portraits and nicknames is not much to say here, which is very simple. The Code is as follows:

-(Uitableviewcell *) tableview :( uitableview *) tableview cellforrowatindexpath :( nsindexpath *) indexpath {static nsstring * cellidentifier = @ "fanscell"; fanscell * cell = [tableview progress: Expected forindexpath: indexpath]; If (cell = nil) {Cell = [[fanscell alloc] initwithstyle: uitableviewcellstyledefault reuseidentifier: cellidentifier];} // here, the user class indicates a fan user * auser = [[user alloc] init]; auser = [_ followersmutablearray objectatindex: [indexpath row]; cell. namelabel. adjustsfontsizetofitwidth = yes; cell. namelabel. TEXT = auser. namestring; // set the cell key text. fansbuttonlabel. titlelabel. adjustsfontsizetofitwidth = yes; If (auser. following) {// indicates that I have followed this fan [cell. fansbuttonlabel settitle: @ "mutual interest" forstate: uicontrolstatenormal];} else {[cell. fansbuttonlabel settitle: @ "+ follow" forstate: uicontrolstatenormal];} // set the Avatar _ block nsdata * imagedata; dispatch_async (dispatch_get_global_queue (0, 0 ), ^ {dispatch_sync (dispatch_get_global_queue (0, 0), ^ {imagedata = [[nsdata alloc] initwithcontentsofurl: [nsurl urlwithstring: auser. profileimageurl];}); dispatch_sync (dispatch_get_main_queue (), ^ {uiimage * image = [[uiimage alloc] initwithdata: imagedata]; [cell. imageview setimage: Image] ;}); // sets calayer * l = [cell. imageview layer]; // obtain the imageview layer [L setmaskstobounds: Yes]; [L setcornerradius: 6.0]; // set the fan ID, here, we only use cell to cancel or add the following request parameters. fansuidstring = auser. idstring; return cell ;}

Note:

1. Set the Avatar to a rounded corner.# Import "quartzcore/quartzcore. H ",You can understand everything else.

2. The method for getting an avatar is as follows:

-(UIImage *) getImageFromURL:(NSString *)fileURL {    UIImage * resultImage = [[UIImage alloc] init];    NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];    resultImage = [UIImage imageWithData:data];    return resultImage;}

In this part, it is worth noting that the button I added is processed. First, let's talk about the role of this button: the following two items are available in the JSON data of the fans: follow_me and following. The former indicates whether the fans are interested in me, obviously, my fans are interested in me, so true is always returned; the latter indicates whether or not I care about this fan, and true is returned if I care about it; otherwise, false is returned. So we can do something here.

If I do not pay attention to this fan, that is, if following is false, the function of the button is to add attention to this fan. The label of the button is "+ follow ".

If I followed this fan, that is, if following is true, the function of the button is to remove the followers, and the label of the button is "Remove follow ";

Because of this processing, I have definedFanscell classIt is used to process the cell content.

The following describes how to follow and remove followers.

① Request API and Parameters

Add follow API: https://api.weibo.com/2/friendships/create.json

Remove followed API: https://api.weibo.com/2/friendships/destroy.json

In addition to access_token, the required parameters also include the UID or screen_name of the fans. Note that the former is of the long (int64) type and the latter is of the string type, I chose the UID parameter.

② Fanscell

These include:

-(Ibaction) fansbutton :( ID) sender; @ property (weak, nonatomic) iboutlet uibutton * fansbuttonlabel; @ property (weak, nonatomic) iboutlet uilabel * namelabel; @ property (weak, nonatomic) iboutlet uiimageview * headimageview; @ property (strong, nonatomic) nsstring * fansuidstring; // fan uid

The fansbutton method is used to handle followers and remove followers.

The following describes the process code:

-(Ibaction) fansbutton :( ID) sender {destroyfriendships = no; creatfriendships = no; If ([self. fansbuttonlabel. titlelabel. text isequaltostring: @ "mutual interest"]) {destroyfriendships = yes; uialertview * Alert = [[uialertview alloc] initwithtitle: @ "prompt" message: @ "cancel follow" delegate: self cancelbuttontitle: @ "cancel" otherbuttontitles: @ "OK", nil]; [alert show];} else if ([self. fansbuttonlabel. titlelabel. text issimilar String: @ "+ follow"]) {creatfriendships = yes; uialertview * Alert = [[uialertview alloc] initwithtitle: @ "prompt" message: @ "follow" delegate: self cancelbuttontitle: @ "cancel" otherbuttontitles: @ "OK", nil]; [alert show] ;}}- (void) alertview :( uialertview *) alertview clickedbuttonatindex :( nsinteger) buttonindex {// cancel if (destroyfriendships & buttonindex = 1) {mbprogresshud * custuonhud = [[mbprogresshud alloc] ini T]; custuonhud. customview = [[uiimageview alloc] initwithimage: [uiimage imagenamed: @ "37x-checkmark.png"]; custuonhud. mode = custom; [self addsubview: custuonhud]; nsurl * url = [nsurl urlwithstring: friendships_destroy]; optional * Item = [[paialloc] initwithurl: url]; [item setpostvalue: [infoforsina returnaccesstokenstring] forkey: @ "access_token"]; [item Setpostvalue: [nsstring stringwithformat: @ "% LLD", [_ fansuidstring longlongvalue] forkey: @ "uid"]; [item setcompletionblock: ^ {[self. fansbuttonlabel settitle: @ "+ follow" forstate: uicontrolstatenormal]; custuonhud. labeltext = @ "the follow has been canceled! "; [Custuonhud show: Yes]; [custuonhud hide: Yes afterdelay: 2];}]; [item setfailedblock: ^ {custuonhud. labeltext = @" An error occurred while canceling the attention! "; [Custuonhud show: Yes]; [custuonhud hide: Yes afterdelay: 2] ;}]; [item startasynchronous];} // Add follow else if (creatfriendships & buttonindex = 1) {// use the ASI class library to process the data requests that have been added to follow/* mbprogresshud * custuonhud = [[mbprogresshud alloc] init]; custuonhud. customview = [[uiimageview alloc] initwithimage: [uiimage imagenamed: @ "37x-checkmark.png"]; custuonhud. mode = mbprogresshudmodecustomview; [self addsubview: c Ustuonhud]; nsurl * url = [nsurl urlwithstring: friendships_creat]; asiformdatarequest * Item = [asiformdatarequest alloc] initwithurl: url]; [item setpostvalue: [infoforsina encrypted] forkey: @ "access_token"]; [item setpostvalue: [nsstring stringwithformat: @ "% LLD", [_ fansuidstring longlongvalue] forkey: @ "uid"]; [item setcompletionblock: ^ {[self. fansbuttonlabel settitle: @ "mutual interest" forstate: u Icontrolstatenormal]; custuonhud. labeltext = @ "followed successfully! "; [Custuonhud show: Yes]; [custuonhud hide: Yes afterdelay: 1] ;}]; [item setfailedblock: ^ {custuonhud. labeltext = @" failed to follow! "; [Custuonhud show: Yes]; [custuonhud hide: Yes afterdelay: 1] ;}]; [item startasynchronous]; * // This class library does not use ASI to process nsurl * url = [nsurl urlwithstring: friendships_creat]; nsmutableurlrequest * request = [descrirequestwithurl: URL cachepolicy: descritimeoutinterval: 5.0]; [Request sethttpmethod: @ "Post"]; nsstring * poststring = [nsstring stringwithformat: @ "AC Cess_token = % @ & uid = % LLD ", [infoforsina metadata], [_ fansuidstring longlongvalue]; nsmutabledata * postdata = [[nsmutabledata alloc] init]; [postdata appenddata: [poststring datausingencoding: nsutf8stringencoding]; [Request sethttpbody: postdata]; self. connection = [[nsurlconnection alloc] initwithrequest: Request delegate: Self startimmediately: Yes] ;}# Pragma mark-nsurlconnection Deleg Ate methods-(void) connection :( nsurlconnection *) connection didreceiveresponse :( nsurlresponse *) response {self. responsedata = [[nsmutabledata alloc] initwithlength: 0];}-(void) connection :( nsurlconnection *) connection didreceivedata :( nsdata *) Data {[self. responsedata appenddata: Data];}-(void) connectiondidfinishloading :( nsurlconnection *) THECONNECTION {mbprogresshud * custuonhud = [[mbprogresshud alloc] Init]; custuonhud. customview = [[uiimageview alloc] initwithimage: [uiimage imagenamed: @ "37x-checkmark.png"]; custuonhud. mode = mbprogresshudmodecustomview; [self addsubview: custuonhud]; nserror * error; nsdictionary * dict = [nsjsonserialization jsonobjectwithdata: Self. responsedata options: kniloptions error: & error]; nsstring * idstring = [dict objectforkey: @ "idstr"]; If (idstring) {[self. fansbutton Label settitle: @ "mutual interest" forstate: uicontrolstatenormal]; custuonhud. labeltext = @ "followed successfully! "; [Custuonhud show: Yes]; [custuonhud hide: Yes afterdelay: 2.3];} else {custuonhud. labeltext = @" failed to follow! "; [Custuonhud show: Yes]; [custuonhud hide: Yes afterdelay: 2.3];} [self. connection cancel];}-(void) connection :( nsurlconnection *) THECONNECTION didfailwitherror :( nserror *) error {mbprogresshud * failedhud = [[mbprogresshud alloc] init]; failedhud. mode = mbprogresshudmodetext; failedhud. labeltext = @ "prompt"; failedhud. detailslabeltext = @ "An error occurred while posting comments! "; [Failedhud show: Yes]; [self addsubview: failedhud]; [failedhud hide: Yes afterdelay: 1.3]; [self. Connection cancel];}

Note:

1. When you press this button, a uialertview is triggered, prompting whether to confirm or cancel the follow.


2. Confirm that you want to follow or cancel the followers in the delegate method of uialertview.

3. The method of following and removing followers is post. We can use asihttprequest for asynchronous processing, or use the built-in method of asynchronous post processing without using this class library. The two methods are used in the code. Here, I used asihttprequest to cancel the follow, and added the follow to use the built-in method (of course, the comments section also provides the use code of asihttprequest ).

Note: If you use the built-in asynchronous post processing method, I have added two properties:

@ Property (strong, nonatomic) nsurlconnection * connection;
@ Property (strong, nonatomic) nsmutabledata * responsedata;

The Code clearly shows that the previous method is very simple, and the latter method is a little troublesome because it is necessary to implement the delegate method!

4. At the end of the data request, I continue to use the mbprogresshud class library to add some prompts, indicating whether the follow is successful or not. The effect is as follows:



This page is almost like this!


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.