Open-source Chinese IOS client learning-(12) User Login

Source: Internet
Author: User

In the previous blog's open-source Chinese IOS client study-(11) What is the process of saving the user name and password to the local sandbox and reading the user name and password from the local machine?

-(void)saveUserNameAndPwd:(NSString *)userName andPwd:(NSString *)pwd{    NSUserDefaults * settings = [NSUserDefaults standardUserDefaults];    [settings removeObjectForKey:@"UserName"];    [settings removeObjectForKey:@"Password"];    [settings setObject:userName forKey:@"UserName"];        pwd = [AESCrypt encrypt:pwd password:@"pwd"];        [settings setObject:pwd forKey:@"Password"];    [settings synchronize];}

The above method uses the nsuserdefaults class, which also implements the data function in the form of a dictionary and saves the data to the local application sandbox. This method is suitable for storing small data, for example, the user logs in to the configuration information. This code first defines an object for initialization and removes the objects whose key values are usename and password to prevent interference caused by data confusion; then, you can reset the key value information; [settings synchronize]; synchronize the key value information to the local directory;

Now let's look at the user configuration information in the sandbox.

First, check the application sandbox path and use

 
    NSString *homeDirectory = NSHomeDirectory();    NSLog(@"path:%@", homeDirectory);

Print result: Path:/users/Dolby/library/Application Support/iPhone simulator/5.1/applications/55c49712-ad95-49e0-b3b9-694dc7d26e94

But there is no library directory under my Dolby user, because the system hides these file directories. Now you need to display these hidden files and open the terminal and enter defaults write COM. apple. finder appleshowallfiles-bool true press enter, and then restart the finder (no? See the IOS sandbox (sanbox) file. Find the net. oschina. iosapp. plist file under library/preferences in the 55c49712-ad95-49e0-b3b9-694dc7d26e94 directory and open it.





It is not difficult to see some basic information of the user stored in the local sandbox, as well as some configuration information, as well as the time when the data was last acquired;


Log on to the loginview class under the setting directory. Check loginview. XIB first. The interface is relatively simple. It may be missing an artist;


Declare part of the file from scratch

# Import <uikit/uikit. h> # import "tool. H "# import" profilebase. H "# import" messageview. H "# import" config. H "# import" mbprogresshud. H "# import" mythread. H "@ interface loginview: uiviewcontroller <uiwebviewdelegate> {// ASI class library, obtain network requests, perform login verification asiformdatarequest * request;} // accept username input @ property (strong, nonatomic) iboutlet uitextfield * txt_name; // the user's password @ property (strong, nonatomic) iboutlet uitextfield * txt_pwd is accepted; // The switch button, set whether the user should remember the user name and password @ property (strong, nonatomic) iboutlet uiswitch * switch_remember; // mark the role, used to record whether a warning @ property bool ispopupbynotice is prompted when an exception or error is returned in the request data; // webview, layout a web page on the mobile phone and display the description information, if rich text is used on this web page, you can directly jump to the URL @ property (strong, nonatomic) iboutlet uiwebview * webview; // login processing-(ibaction) click_login :( ID) sender; // cancel the first response object of two textfiles-(ibaction) textend :( ID) sender; // cancel the first response object of the keyboard, click the keyboard that is displayed on the page-(ibaction) backgrondtouch :( ID) sender; // Save the user name and user ID to the local device based on the returned data-(void) analyseuserinfo :( nsstring *) XML; @ end

Paste the main method code in the implementation file

-(Void) viewdidload {[Super viewdidload]; [Tool clearwebviewbackground: webview]; [self. webview setdelegate: Self]; self. navigationitem. title = @ "login"; // determines whether the user name and password nsstring * name = [config instance] are displayed. getUserName; nsstring * Pwd = [config instance]. getpwd; // if the user name and password exist and are not empty, the corresponding text if (Name &&! [Name isequaltostring: @ ""]) {self.txt _ name. Text = Name;} If (PWD &&! [PWD is1_tostring: @ ""]) {self.txt _ PWD. TEXT = PWD;} uibarbuttonitem * btnlogin = [[uibarbuttonitem alloc] initwithtitle: @ "login" style: uibarbuttonitemstylebordered target: Self action: @ selector (click_login. navigationitem. rightbarbuttonitem = btnlogin; self. view. backgroundcolor = [Tool getbackgroundcolor]; self. webview. backgroundcolor = [Tool getbackgroundcolor]; // nsstring * html = @ "<body style = 'background-color: # ebebf3'> 1, you can register an account on the <a href = 'HTTP: // www.oschina.net '> http://www.oschina.net </a> for free to log in <p/> 2, if your account is registered using openid, we recommend that you set a password for the account on the Web page <p/> 3. You can click <a href = 'HTTP: // www.oschina.net/question/12_52232'> here </a> learn more about logon to the mobile client </body> "; [self. webview loadhtmlstring: HTML baseurl: Nil]; self. webview. hidden = no ;}

In [toolclearwebviewbackground: webview], the function description is not good. You can view the method directly.

+ (void)clearWebViewBackground:(UIWebView *)webView{    UIWebView *web = webView;    for (id v in web.subviews) {        if ([v isKindOfClass:[UIScrollView class]]) {            [v setBounces:NO];        }    }}

[V
Setbounces: No]; if [V setbounces: Yes]; if the scroll is up or down, there is a gap. If the scroll is no, it will not;


-(Ibaction) click_login :( ID) sender {// obtain the username and password nsstring * name = self.txt _ name. text; nsstring * Pwd = self.txt _ PWD. text; // use the ASI class library to request the login API. Request = [asiformdatarequest requestwithurl: [nsurl urlwithstring: Required]; [Request setusecookiepersistence: Yes]; [Request setpostvalue: Name forkey: @ "username"]; [Request setpostvalue: Pwd forkey: @ "PWD"]; [Request setpostvalue: @ "1" forkey: @ "keep_login"]; [Request setdelegate: self]; // call requestfailed failed: [Request setdidfailselector: @ selector (requestfailed :)]; // equestlogin: [Request setdidfinishselector: @ selector (requestlogin :)]; // start the request [Request startasynchronous]; // The animation prompts the user to wait for the request. HUD = [[mbprogresshud alloc] initwithview: Self. view]; [Tool showhud: @ "logging on" andview: Self. view andhud: request. HUD];}
 
// Login Failed. Hide the displayed animation-(void) requestfailed :( asihttprequest *) Request {If (request. HUD) {[request. HUD hide: Yes];}


-(Void) requestlogin :( asihttprequest *) Request {If (request. HUD) {[request. HUD hide: Yes];} // parse the data based on the XML returned from the request to determine whether the login is successful. [Tool getoscnotice: request]; // Save the request back information on the client [Request setusecookiepersistence: Yes]; apierror * error = [Tool getapierror: request]; If (error = nil) {[Tool toastnotification: request. responsestring andview: Self. view andloading: No andisbottom: No];} switch (error. errorcode) {Case 1: {[config instance] savecookie: Yes]; If (ispopupbynotice = No) {nsuserdefaults * D = [nsuserdefaults standarduserdefaults]; [self. navigationcontroller popviewcontrolleranimated: Yes];} // determines whether to remember the user name or password if (self. switch_remember.ison) {[[config instance] saveusernameandpwd: self.txt _ name. text andpwd: self.txt _ PWD. text];} // otherwise, you need to clear the username in the password else {[[config instance] saveusernameandpwd: @ "" andpwd: @ ""];} // process the returned result if ([config instance]. viewbeforelogin) {If ([[config instance]. viewnamebeforelogin isw.tostring: @ "profilebase"]) {profilebase * _ parent = (profilebase *) [config instance]. viewbeforelogin; _ parent. isloginjustnow = yes; }}// start to analyze UID and other information [self analyseuserinfo: request. responsestring]; // whether the analysis needs to be returned if (self. ispopupbynotice) {[self. navigationcontroller popviewcontrolleranimated: Yes];} // The startnotice method indicates that a timer is used to refresh user information every 60 s, whether there are new fans or several comments [[mythread instance] startnotice];} break; Case 0: case-1: {// return an error. errorcode = 0 | 1, the error message [Tool toastnotification: [nsstring stringwithformat: @ "error % @", error. errormessage] andview: Self. view andloading: No andisbottom: No];} break ;}}

The apierror class may seem confusing. It does not mean the wrong API information exactly as it literally, but is determined based on the number returned by the request. If error. errorcode = 1 indicates that user data is successfully returned. If the value is 0 or-1, data cannot be returned due to server network or other reasons;

In apierror * error = [Tool getapierror: request];, print request. responsestring as follows,

<? XML version = "1.0" encoding = "UTF-8"?> <Oschina> <result> <errorcode> 1 </errorcode> <errormessage> <! [CDATA [logon successful]> </errormessage> </result> <user> <uid> 112617 </uid> <location> <! [CDATA [Nanyang, Henan]> </location> <Name> <! [CDATA [wind and waves]> </Name> <followers> 1 </followers> <fans> 0 </fans> <score> 1 </score> <portrait> http://static.oschina.net/uploads/user/56/112617_100.jpg? T = 1350377690000 </portrait> </user> <notice> <atmecount> 0 </atmecount> <msgcount> 0 </msgcount> <reviewcount> 0 </reviewcount> <newfanscount> 0 </newfanscount> </notice> </oschina> <! -- Generated by oschina. Net (init: 3 [MS], page: 3 [MS], IP: 61.163.231.198) -->

In the [self analyseuserinfo: request. responsestring] method, the username and uid are parsed Based on the XML returned by the successful request, and the UID is saved.

-(Void) analyseuserinfo :( nsstring *) XML {@ try {tbxml * _ xml = [[tbxml alloc] initwithxmlstring: XML error: Nil]; tbxmlelement * root = _ xml. rootxmlelement; tbxmlelement * user = [tbxml childelementnamed: @ "user" parentelement: Root]; tbxmlelement * uid = [tbxml childelementnamed: @ "uid" parentelement: User]; // obtain uid [[config instance] saveuid: [[tbxml textforelement: uid] intvalue];} @ catch (nsexception * exception) {[nduncaughtexceptionhandler takeexception: exception];} @ finally {}}

You can also see [[mythread instance] startnotice] Later. Check whether the startnotice method is a timer. Refresh the user information every 60 s and check whether there are new fans or comments;

-(void)startNotice{    if (isRunning) {        return;    }    else {        timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];        isRunning = YES;    }}

-(void)timerUpdate{    NSString * url = [NSString stringWithFormat:@"%@?uid=%d",api_user_notice,[Config Instance].getUID];    [[AFOSCClient sharedClient]getPath:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {                [Tool getOSCNotice2:operation.responseString];            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {            }];    }

Information returned by the URL request (if you have logged on to the open-source Chinese community website)

<oschina><notice><atmeCount>0</atmeCount><msgCount>0</msgCount><reviewCount>0</reviewCount><newFansCount>0</newFansCount></notice></oschina><!-- Generated by OsChina.NET (init:1[ms],page:1[ms],ip:61.163.231.198) -->


For more information about the transition display effects of the animation mentioned in this article, see

[Tool showhud: @ "logging on" andview: Self. View andhud: request. HUD]; mbprogresshud special effect

[Tool toastnotification: [nsstring stringwithformat: @ "error % @", error. errormessage] andview: Self. View andloading: No andisbottom: No]; gcdiscreetnotificationview prompt View




Original blog welcome to repost share, please indicate the source of http://blog.csdn.net/duxinfeng2010

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.