ios webservice登录

来源:互联网 发布:关于网络诈骗的新闻 编辑:程序博客网 时间:2024/06/01 07:55

转自  http://blog.csdn.net/xrhdz/article/details/8549090


新建一个程序,选single view application

名称为LoginWebservice,arc挑勾


程序建成


在LoginWebService_ViewController.h里添加<NSXMLParserDelegate,NSURLConnectionDelegate>协议,然后添加代码如下:


#import <UIKit/UIKit.h>

@interface LoginWebService_ViewController : UIViewController
<NSXMLParserDelegate,NSURLConnectionDelegate>
{
    UITextField *txtName;
    UITextField *txtPassword;
}

@property (nonatomic,retain) IBOutlet UITextField *txtName;
@property (nonatomic,retain) IBOutlet UITextField *txtPassword;
@property (nonatomic,retain) IBOutlet UITextView *txtStatus;

@property (nonatomic,retain) NSMutableDictionary *jsonDicUser;
@property (nonatomic,retain) NSMutableData *webData;
@property (nonatomic,retain) NSMutableString *soapResults;
@property (nonatomic,retain) NSXMLParser *xmlParser;
@property (nonatomic,retain) NSString *matchingElement;
@property (nonatomic,retain) NSURLConnection *conn;
@property (strong, nonatomic) IBOutlet UILabel *labelText;
@property (nonatomic) BOOL elementFound;
-(IBAction)loginButton:(id)sender;


@end

创建UI视图.xib文件两个label, 两个textField,一个textView,一个button


建立关联txtName,txtPassword,txtStatus,loginButton


.h中添加代码,下面是原始代码

#import "LoginWebService_ViewController.h"


@interface LoginWebService_ViewController ()


@end


@implementation LoginWebService_ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}


@end

改成

#import "LoginWebService_ViewController.h"


@interface LoginWebService_ViewController ()


@end


@implementation LoginWebService_ViewController
@synthesize txtName;
@synthesize txtPassword;
@synthesize txtStatus;
@synthesize webData;
@synthesize soapResults;
@synthesize xmlParser;
@synthesize matchingElement;
@synthesize conn;
@synthesize labelText;
@synthesize elementFound;

//点击屏幕如何地方,键盘隐藏
- (IBAction)backgroundTap:(id)sender {
    [txtName resignFirstResponder];
    [txtPassword resignFirstResponder];
    [txtStatus resignFirstResponder];
}


- (IBAction)loginButton:(id) sender{
    
    
    NSString *name = txtName.text;
    NSString *pwd = txtPassword.text;
    // 设置我们之后解析XML时用的关键字,与响应报文中Body标签之间的DictionaryQueryResult标签对应
    matchingElement = @"UserInfoCheckResult";
    // 创建SOAP消息,内容格式就是网站上提示的请求报文的实体主体部分
    NSString *soapMsg = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                         "<soap12:Envelope "
                         "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
                         "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
                         "xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"
                         "<soap12:Body>"
                         "<UserInfoCheck xmlns=\"XJ.WebService\">"
                         "<用户名>%@</用户名>"
                         "<用户密码>%@</用户密码>"
                         "</UserInfoCheck>"
                         "</soap12:Body>"
                         "</soap12:Envelope>", name ,pwd ];
    
    // 将这个XML字符串打印出来
    NSLog(@"%@", soapMsg);   
    // 创建URL,内容是前面的请求报文报文中第二行主机地址加上第一行URL字段
    NSURL *url = [NSURL URLWithString: @"服务器地址"];
    // 根据上面的URL创建一个请求
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMsg length]];
    // 添加请求的详细信息,与请求报文前半部分的各字段对应
    [req addValue:@"application/soap+xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    // 设置请求行方法为POST,与请求报文第一行对应
    [req setHTTPMethod:@"POST"];
    // 将SOAP消息加到请求中
    [req setHTTPBody: [soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
    // 创建连接
    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if (conn) {
        webData = [NSMutableData data];
    }
    
}


#pragma mark -
#pragma mark URL Connection Data Delegate Methods


// 刚开始接受响应时调用
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response{
    [webData setLength: 0];
}


// 每接收到一部分数据就追加到webData中
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *) data {
    [webData appendData:data];
}


// 出现错误时
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *) error {
    conn = nil;
    webData = nil;
}


// 完成接收数据时调用
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
    NSString  *theXML = [[NSString alloc] initWithBytes:[webData mutableBytes]
                                                 length:[webData length]
                                               encoding:NSUTF8StringEncoding];
    
    // 打印出得到的XML
    NSLog(@"%@", theXML);
    
    // 使用NSXMLParser解析出我们想要的结果
    xmlParser = [[NSXMLParser alloc] initWithData: webData];
    [xmlParser setDelegate: self];
    [xmlParser setShouldResolveExternalEntities: YES];
    [xmlParser parse];
}


#pragma mark -
#pragma mark XML Parser Delegate Methods


// 开始解析一个元素名
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *) qName attributes:(NSDictionary *) attributeDict {
    if ([elementName isEqualToString:matchingElement]) {
        if (!soapResults) {
            soapResults = [[NSMutableString alloc] init];
        }
        elementFound = YES;
    }
}


// 追加找到的元素值,一个元素值可能要分几次追加
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string {
    if (elementFound) {
        [soapResults appendString: string];
    }
}








// 结束解析这个元素名
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    
    
    if(txtName.text.length==0||txtPassword.text.length==0)
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"用户名或密码不能为空!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alertView show];
        elementFound = FALSE;
        // 强制放弃解析
        [xmlParser abortParsing];
    }
    else {
        
        
        if ([soapResults isEqualToString:@"-1"]) {
            
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示"
                                                               message:@"用户名或密码错误!"
                                                              delegate:nil
                                                     cancelButtonTitle:@"确定"
                                                     otherButtonTitles:nil];
            [alertView show];
            txtStatus.text=soapResults;
            elementFound = FALSE;
            // 强制放弃解析
            [xmlParser abortParsing];
        }
        else {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示"
                                                               message:@"登录成功!"
                                                              delegate:nil
                                                     cancelButtonTitle:@"确定"
                                                     otherButtonTitles:nil];
            [alertView show];
            txtStatus.text= soapResults;
            //  txtStatus.text=[soapResults valueForKey:@"用户名"];
            
            //labelText.text=[soapResults valueForKey:@"员工编号"];
            // labelText.text=[NSString stringWithFormat:@"%@",[ soapResults valueForKey:@"员工编号"]];
            elementFound = FALSE;
            // 强制放弃解析
            [xmlParser abortParsing];
        }
    }
    
}


// 解析整个文件结束后
- (void)parserDidEndDocument:(NSXMLParser *)parser {
    if (soapResults) {
        soapResults = nil;
    }
}


// 出错时,例如强制结束解析
- (void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    if (soapResults) {
        soapResults = nil;
    }
}


- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}


@end

 

 

注:红色字有注意,结合自己的值写,如上图

 

 

大功告成,结果如下图:


登录webservice完成,希望对大家有所帮助,希望和大家共同进步,欢迎留言交流


0 0