原文地址: 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數據 |
|
ASIHTTPRequest |
HTTP的封裝 |
|
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解析,方法如下: