使用ASIFormDataRequest完成用户的登录操作

ASIFormDataRequest是用于向表单post数据或get数据,可以用于用户向服务器端发送请求完成登录注册,上传下载数据的操作。

之前写过一篇文章是介绍使用ios内置的功能完成登录操作(NSMutableURLRequest 用法,一个结合PHP后台程序用户登录的例子),现在我们使用ASIFormDataRequest来完成用户的登录操作
首先我们在apache服务器创建一个login.php的文件,文件内容为:
<?php
header("Content-type: text/html; charset=utf-8"); 
    $username=$_POST['username'];
    $password=$_POST['password'];
    if (empty($username) && empty($password)){
            echo "您输入的值为空";
    }else{
            echo "您的姓名为:".$username;
    }
?>
接下来我们就开始我们的工作:
(关于ASIHTTPRequest这个框架的介绍及使用方法就不多说了,自己搜索或看本站相关的介绍。以后关于本站有关ASIHTTPRequest均不介绍了,也不介绍如何使用和导入)

第一步:在login.xib界面上放置一个两个登录筐,一个是用户名一个是密码,然后再放置一个登录的按钮
第二步:假设我们定义的登录文件名称为login,则login.h里面的内容为:

#import <UIKit/UIKit.h>
// 在m文件导入一个外部类,则在h文件里面定义该外部类的class名,则h文件里面无需导入外部类也可以进行访问外部类里面的内容
@class ASIFormDataRequest;
@interface login : UIViewController{
//定义一个ASIFormDataRequest对象
    ASIFormDataRequest *request;
}
//定义用户名和密码两个输入框
@property (weak, nonatomic) IBOutlet UITextField *username;
@property (weak, nonatomic) IBOutlet UITextField *password;
//定义登录按钮事件
- (IBAction)loginAction:(id)sender;
@property (retain, nonatomic) ASIFormDataRequest *request;
@property (weak, nonatomic) IBOutlet UITextView *txt;
@end

第 三步:定义login. m文件里面的内容:
#import "login.h"
#import "ASIFormDataRequest.h"
 
@interface login ()
-(void)loginFailed:(ASIHTTPRequest *)reuqest;
-(void)loginSucceed:(ASIHTTPRequest *)reuqest;
@end
 
@implementation login
@synthesize activity;
@synthesize txt;
@synthesize username;
@synthesize password;
@synthesize request;
 
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
 
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
 
- (void)viewDidUnload
{
    [self setUsername:nil];
    [self setPassword:nil];
    [self setActivity:nil];
    [self setTxt:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (IBAction)loginAction:(id)sender {
    
    //先中断连接吧
    [request cancel];
//第一步,创建请求地址(创建请求地址有这两种方式,都是一样的)
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://www.wiaphone.com/login.php"]];
    //ASIFormDataRequest *request=[[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.wiaphone.com/login.php"]];
    
    NSLog(@"%@",request);
    //设置返回的数据的编码
    [request setDefaultResponseEncoding:NSUTF8StringEncoding];
//设置连接事件如果超过20秒就报错
    [request setTimeOutSeconds:20];
//使用ASIFormDataRequest必须要要写这3句话,请求成功与请求失败的情况
    [request setDelegate:self];
    [request setDidFailSelector:@selector(loginFailed:)];
    [request setDidFinishSelector:@selector(loginSucceed:)];
    
/*
在使用ios内置的功能发送post请求比较麻烦,你需要这么做:
//得到我们所输入的数据
NSString *getUserInfo=[NSString stringWithFormat:@"username=%@&password=%@",username.text,password.text];
//对传过去的数据进行编码处理,
NSData *dealPostData=[getUserInfo dataUsingEncoding:NSUTF8StringEncoding];
//得到一个url对象,使用URLWithString方法初始化一个url对象
NSURL *webController=[NSURL URLWithString:@"http://www.zpluz.com/logo.php"];
//创建一个request对象,就是说创建一个请求的对象
//NSMutableRequest是NSURLRequest的一个子类
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:webController];
//因为我们已经创建了一个http请求对象request,所以我们需要对该对象进行请求类型设置为post(用户名和密码登陆需要进行安全请求,所以必须为post)
[request setHTTPMethod:@"POST"];
//设置http请求头部信息,比如实例中的请求地址:http://www.wiaphone.com/login.php?username=villardlee&password=123456,其中username=villardlee&password=123456就是一个http的头部信息
[request setHTTPBody:dealPostData];
//使用NSURLConnection开始发送http请求
//到这一步,NSURLConnection会自动调用一些方法(委托事件),包括接收数据委托方法(委托1);返回数据(或者说输出数据)的方法(委托2);接收数据失败(委托3)
NSURLConnection *sendRequest=[[NSURLConnection alloc] initWithRequest:request delegate:self
                                  ];
而ASIFormDataRequest简化为:
ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://www.wiaphone.com/login.php"]];
[request setPostValue:self.username.text forKey:@"username"];
[request setPostValue:self.password.text forKey:@"password"];

自己仔细看看两者之间的区别吧!!
*/
    [request setPostValue:self.username.text forKey:@"username"];
    [request setPostValue:self.password.text forKey:@"password"];
    
    
    //开始进行同步请求
    [request startAsynchronous];
    NSLog(@"***************");
}
//如果请求失败
-(void)loginFailed:(ASIHTTPRequest *)reuqest{
    NSLog(@"访问失败");
    [txt setText:[NSString stringWithFormat:@"Request failed: %@",[[reuqest error] localizedDescription]]];
}
//如果请求成功
-(void)loginSucceed:(ASIHTTPRequest *)request{
    NSLog(@"访问成功");
    
    //这里的字节指的是http://www.wiaphone.com/login.php后面的传输的数据
    NSLog([NSString stringWithFormat:@"总共传送了 %llu 字节的数据",[request postLength]]);
    
    //获取请求的头部信息
    NSMutableDictionary *headerData=[request requestHeaders];
    NSLog(@"%@",headerData);
    NSLog(@"所有的键:%@",headerData.allKeys);
    NSLog(@"所有的值:%@",headerData.allValues);
    NSLog(@"User-Agent:%@",[headerData objectForKey:@"User-Agent"]);
    NSLog(@"Content-Type:%@",[headerData objectForKey:@"Content-Type"]);
    NSLog(@"Content-Length:%@",[headerData objectForKey:@"Content-Length"]);
    NSLog(@"Accept-Encoding:%@",[headerData objectForKey:@"Accept-Encoding"]);
    
    //下面是两者获取返回数据并输出数u的方法,前一种比肩简单,直接是string返回;而后一种进行编码后输出

    NSString *requestData=[request responseString];
    NSLog(@"%@",requestData);
    [txt setText:requestData];
    
    NSData *udata=[request responseData];
    NSStringEncoding encodeUdata=CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingUTF8);
    NSString *getUserData=[[NSString alloc] initWithData:udata encoding:encodeUdata];
    NSLog(@"%@",getUserData);
    
}
@end
原文地址:https://www.cnblogs.com/hjltonyios/p/5015798.html