现在的位置: 首页 > 综合 > 正文

分享一个用Xcode4实现基于Webservice用户登录的iphone程序

2012年08月05日 ⁄ 综合 ⁄ 共 5632字 ⁄ 字号 评论关闭

最近论坛里面iphone开发的文章貌似多起来了,刚好我最近也在学Objective-c,忍耐不住寂寞啊,做了个登录Demo给将要入门的博友参考参考,也请大牛不腻赐教。好吧,我承认我才入门一个星期,上周才把mac系统装好。

需求很简单:

界面上有三个输入框,分别是服务器地址、用户名、密码(这里的服务器地址仅仅是为了我个人调试所用)

输入帐号密码,点击登录,如服务器地址有误提示则提示“服务器未相应”;

若登录成功,将用户名和密码以对话框的形式打印出来;

若登录失败,提示返回信息;

iphone手机上大多软件都免不了登录吧,当然iphone程序又不像.Net那样,可以很方便的操作数据库,所以这里采取Web API的方式。首先用vs创建一个Web Service,这个很简单,代码如下:

        /// <summary>
        
/// 验证用户登录
        
/// </summary>
        
/// <param name="userName">用户名称</param>
        
/// <param name="pwd">用户密码</param>
        
/// <returns>返回验证结果</returns>
        [WebMethod]
        
public String CheckLoginUserInfo(string userName, string pwd)
        {
            XmlDocument document 
= new XmlDocument();
            Func
<String, String, XmlNode> func = new Func<String, String, XmlNode>((nodeName, innterText) =>
            {
                XmlNode node 
= document.CreateNode("element", nodeName, "");
                node.InnerText 
= innterText;
                
return node;
            });

            XmlNode rootElem = func("result""");
            XmlNode data 
= func("data""");
            String isSuccess 
= "0";
            
if (userName == "test" && pwd == "123456")
            {
                isSuccess 
= "1";
                data.AppendChild(func(
"truename""测试人员1"));
                data.AppendChild(func(
"userroleid""1"));
                data.AppendChild(func(
"depid""2"));
                data.AppendChild(func(
"depname""编辑中心-要闻编辑部"));
                data.AppendChild(func(
"paperid""3"));
                data.AppendChild(func(
"papername""解放日报"));
            }
            
else
            {
                data.AppendChild(func(
"message""帐号或密码错误!"));
            }
            rootElem.AppendChild(func(
"isSuccess",isSuccess));
            rootElem.AppendChild(data);
            document.AppendChild(rootElem);
            Console.WriteLine();
            
return document.OuterXml;
        }

用户信息我就不从数据库里面取了,默认正确的就是test123456

我们可以在本地测试下这个服务,保证服务器本身没有问题。

输入错误的用户名和密码如下返回提示信息:

 

输入test123456,返回我们期望的结果,注意是xml格式

 

好了,我们回到iphone这边,开发环境是Mac10.6.6 + Xcode4,新建一个应用程序,程序界面如下,

 

我们在登录界面初始化时给视图设置一个背景,虽然是demo,但也不能太丑吧:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self 
= [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    UIImage 
*bgImage = [UIImage imageNamed:@"background.png"];
    UIImageView 
*bgView = [[UIImageView alloc ]initWithImage:bgImage];
    [self.view insertSubview:bgView atIndex:
0];
    [bgView release];
    
return self;
}

接下就是登录按钮的事件了,声明webservice的请求主体

    NSString *soapMessage = [NSString stringWithFormat:
                             
@"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                             
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                             
"<soap:Body>\n"
                             
"<CheckLoginUserInfo xmlns=\"http://tempuri.org/\">"
                             
"<userName>%@</userName>"
                             
"<pwd>%@</pwd>"
                             
"</CheckLoginUserInfo>"
                             
"</soap:Body>\n"
                             
"</soap:Envelope>\n",account.text,passwd.text];
NSString 
*msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];

这个字符串是不是很熟悉?没错就,打开我们定义的webservice测试页面,可以看到可以看到请求和响应示例;

 

然后声明一个request,设置一些必要的属性,并发送请求接受响应;

    NSURL *url = [NSURL URLWithString:SERVERIP];
    NSMutableURLRequest 
*urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest addValue: 
@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [urlRequest addValue: 
@"http://tempuri.org/CheckLoginUserInfo" forHTTPHeaderField:@"SOAPAction"];
    [urlRequest addValue: msgLength forHTTPHeaderField:
@"Content-Length"];
    [urlRequest setHTTPMethod:
@"POST"];
    [urlRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLResponse 
*reponse;
    NSError 
*error = nil;
    NSData 
*responseData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&reponse error:&error];
    UIAlertView 
*alert = nil;

C#很像吧,感觉有很几年编程基础后,学习一门新语言真的很快,大部分时间都看语法。(这里的“快”仅仅指的是入门);接受到响应后我们开始处理结果,本来想在公司服务器上不是这个Services,结果发现今天公司服务器挂了,很是杯具,我自己只有一台双系统笔记本,想返回xml并解析的,现在不好调试,双系统之间切换好郁闷啊,索引就将返回结果直接以提示框的形式展现出来吧; 

    if(error)
    {
        alert 
= [[UIAlertView alloc]
                 initWithTitle:
@"提示"
                 message:[error description]
                 
delegate:self 
                 cancelButtonTitle:nil 
                 otherButtonTitles:
@"OK", nil]; 
    }
else
    { 
        
if(responseData)
        {
            NSString 
*responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
            NSRange range 
= [responseString rangeOfString:@"truename"];
            
if (range.length) 
            {
                
                alert 
= [[UIAlertView alloc]
                         initWithTitle:responseString                       
                         message:[error description]
                         
delegate:self 
                         cancelButtonTitle:nil 
                         otherButtonTitles:
@"OK", nil]; 
            }
else
            {
                alert 
= [[UIAlertView alloc]
                         initWithTitle:
@"用户名密码错误!"
                         message:[error description]
                         
delegate:self 
                         cancelButtonTitle:nil 
                         otherButtonTitles:
@"OK", nil]; 
            }
        }
    }
    [alert show]; 
    [alert release];

如果请求时error不为null,说明服务器地址有误或其他无法连接服务器等错误,这里我故意将地址少输入了一个0;

如果服务器地址、用户名、密码均没有问题,则直接提示返回的xml;

这里的“测试人员”就是该用户在服务端的真实姓名;

抱歉!评论已关闭.