您的位置:首页 > 移动开发 > IOS开发

如何写一个使用Web Service的IOS应用

2014-10-31 17:07 267 查看
原文地址: http://www.cnblogs.com/cokecoffe/archive/2012/06/17/2552869.html

本教程是来自于

http://www.raywenderlich.com/2965/how-to-write-an-ios-app-that-uses-a-web-service

我很喜欢这个网站的教程,所以翻译过来,并进行了概括,以方便以后回顾。

适合有一定的基础的开发人员,快速实施。如果是初学者,那么请看原文链接,讲的很详细。



一、 前期准备工作:

需要使用的第三方库:
库名称
功能
下载地址
JSON
用来解析Json数据
https://github.com/stig/json-framework/downloads
ASIHTTPRequest
HTTP的封装
http://github.com/pokeb/asi-http-request/tarball/master
MBProgressHUD
进度、状态指示器
https://github.com/matej/MBProgressHUD
接下来就开始创建项目并导入:

1.开启Xcode创建一个项目,项目类型选择Single View Application。

2.创建三个Group,并导入上述三个库。

JSON:将JSON\Classes目录的文件托入刚才创建的JSON GROUP。

ASIHTTPRequest:将ASIHTTPRequest\Classes目录的所有文件拖入创建的ASIHTTPRequest GROUP(注意,只要当前目录的文件,CloudFiles之类的目录不需要)

ASIHTTPRequest\External\Reachability这里的文件也要加进来

MBProgressHUD:将MBProgressHUD.m和MBProgressHUD.h拖入MBProgressHUD GROUP

以上三个操作,拖入的时候,记得勾选Copy items into destination group’s folder (if needed)选项,意思是把目录复制到你的项目中,而不是只引用。

3.导入一些必要的frameworks:点击左侧导航栏中你的项目->选中target->再选择build phases栏0->Link Binary with Libraries。点击+按钮,搜索CFNetwork.framework and SystemConfiguration.framework,MobileCoreServices.framework, and libz.1.2.3.dylib四个库。

以上三个大步骤完成后,点击编译。完成第一个阶段。



二、实现Interface

创建UI: 1.label

2.textfield

3.textview



三、与WebService交互

我们的Web Service需要三个参数:

rw_app_id: 应用的唯一标识号. If you’ve been following along with the previous tutorial, there should be only one entry so far, App ID #1.
code: The code to attempt to redeem. This should be a string that’s entered by the user.
device_id: The device ID that is attempting to redeem this code. We can get this with an easy API call

我们需要使用POST机制请求WebService。ASIHTTPRequest将使这一过程变得很便捷。

1.创建一个ASIFormDataRequest实例与URL

2.使用setPostValue方法指定各个参数

3.设置viewcontroller为request的delegate,之后调用startAsynchronous来发起异步请求

4.当请求完毕后,requestFinished或者requestFailed会被回调

5.requestFinished无论webservice相应一个错误的代码,或者正确响应,都会被调用,所以在这个函数里要检查请求成功或者失败

6.如果一切顺利,再解析收到的JSON数据



- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"Want to redeem: %@", textField.text);
    
    // Get device unique ID
    UIDevice *device = [UIDevice currentDevice];
    NSString *uniqueId= [device uniqueIdentifier];
    
    // Start request
    NSString *code = textField.text;
    NSURL *url = [NSURL URLWithString:@"http://www.wildfables.com/promos/"];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setPostValue:@"1" forKey:@"rw_app_id"];
    [request setPostValue:code forKey:@"code"];
    [request setPostValue:uniqueId forKey:@"device_id"];
    [request setDelegate:self];
    [request startAsynchronous];
    
    // Hide keyword
    [textField resignFirstResponder];
    
    // Clear text field
    textView.text = @"";  
    
    //状态指示器
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"Redeeming code...";
    return TRUE;
}

/*请求完成后回调*/
- (void)requestFinished:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    if (request.responseStatusCode == 400) {
        textView.text = @"Invalid code";        
    } else if (request.responseStatusCode == 403) {
        textView.text = @"Code already used";
    } else if (request.responseStatusCode == 200) {
        NSString *responseString = [request responseString];
        NSDictionary *responseDict = [responseString JSONValue];
        NSString *unlockCode = [responseDict objectForKey:@"unlock_code"];
        
        if ([unlockCode compare:@"com.razeware.test.unlock.cake"] == NSOrderedSame) {
            textView.text = @"The cake is a lie!";
        } else {        
            textView.text = [NSString stringWithFormat:@"Received unexpected unlock code: %@", unlockCode];
        }
        
    } else {
        textView.text = @"Unexpected error";
    }
    
}
/*请求失败后回调*/
- (void)requestFailed:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    NSError *error = [request error];
    textView.text = error.localizedDescription;
}




为了让用户感受到,在请求数据的时候,程序在运行,而不是假死,所以要添加状态指示器。

三个步骤

// Add at the top of the file#import "MBProgressHUD.h"



// Add right before return TRUE in textFieldShouldReturn

MBProgressHUD *hud =[MBProgressHUD showHUDAddedTo:self.view animated:YES];

hud.labelText =@"Redeeming code...";



// Add at start of requestFinished AND requestFailed

[MBProgressHUD hideHUDForView:self.view animated:YES];

编译运行,大功告成。



代码:http://d1xzuxjlafny7l.cloudfront.net/downloads/PromoTest.zip



ps:IOS5.0以上支持JSON解析,方法如下:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐