1. 程式人生 > >IOS如何呼叫WebService?

IOS如何呼叫WebService?

這是一個老外寫的,我覺得不錯,特地轉過來,而且裡面的英語也不是很難,所以就不翻譯了,順便我也收藏一下,呵呵。

As an iOS developer, you often need to use a web service from your app.

Sometimes you need to use a web service that someone else has written, and sometimes you need to use one of your own!

In this tutorial, you’ll get hands-one experience with using web services, by writing an iOS app that communicates with a simple web service that allows you to redeem promo codes to unlock extra content.

This tutorial is the second and final part of a two part series on custom web services. If you are curious how to develop the web service yourself, check out the first part of the series for full details!

You don’t necessarily have to set up the web service yourself for this tutorial – you can use the one I’ve already set up if you’d like.

This tutorial assumes you have basic familiarity with programming for iOS. If you are new to iOS development, you may wish to check out some of the other tutorials on this site first.

The Choice

This tutorial requires you to create a new View-based application and integrate three frameworks into it: the JSON framework, ASIHTTPRequest, and MBProgressHUD. You also have to make a basic UI for the app so the user can enter in a code to redeem.

But that’s a lot of work, so I thought we’d start this tutorial out with a choice. Are you like this guy?

"F that!" guy

If so, then just download this starter project with the libraries pre-integrated and the UI pre-made and skip the next two sections :]

Otherwise, read on DIYer! :]

Do It Yourself!

If you want to create everything yourself, start up Xcode and go to File\New\New Project, select iOS\Application\View-based Application, and click Next. Enter PromoTest for the Product Name, click Next, and save it somewhere.

To add the JSON framework, first download it from its github page. Once you have it downloaded, right click your PromoTest project entry in groups and files, select New Group, and name the new group JSON. Then drag all of the files from the JSON\Classes directory (JSON.h and several others) into the new JSON group. Make sure “Copy items into destination group’s folder (if needed)” is selected, and click Finish.

To add ASIHTTPRequest, first download it. Once you have it downloaded, right click your PromoTest project entry in groups and files, select New Group, and name the new group ASIHTTPRequest. Then drag all of the files from the ASIHTTPRequest\Classes directory (ASIAuthenticationDialog.h and several others, butIMPORTANT! don’t add the subfolders such as ASIWebPageRequest, CloudFiles, S3, and Tests.) into the new ASIHTTPRequest group. Make sure “Copy items into destination group’s folder (if needed)” is selected, and click Finish.

Also repeat this for the two files in ASIHTTPRequest\External\Reachability, as these are dependencies of the project.

To add MBProgressHUD, first download it. Once you have it downloaded, right click your PromoTest project entry in groups and files, select New Group, and name the new group MBProgressHUD. Then drag MBProgressHUD.h and MBProgressHUD.m into the new MBProressHUD group. Make sure “Copy items into destination group’s folder (if needed)” is selected, and click Finish.

The last step is you need to link your project against a few required frameworks. To do this, click on your PromoTest project entry in Groups & Files, click the PromoTest target, choose the Build Phases tab, and expand the Link Binary with Libraries section. Click the plus button in this section, and choose CFNetwork.framework. Then repeat this for SystemConfiguration.framework, MobileCoreServices.framework, and libz.1.2.3.dylib.

Framework Dependencies in Xcode 4

Compile your project just to make sure you’re good so far, and now we’re back to the fun stuff!

Implementing the Interface

Let’s make a quick and simple interface to test this web service. As a refresher, the web service takes three parameters:

  1. rw_app_id: The unique identifier for the app. If you’ve been following along with the previous tutorial, there should be only one entry so far, App ID #1.
  2. code: The code to attempt to redeem. This should be a string that’s entered by the user.
  3. device_id: The device ID that is attempting to redeem this code. We can get this with an easy API call.

So basically, all we need is a text field for the user to enter the code (they’ll tap “Go” on the keyboard to start the redemption process), a label for the text field, and a text view to write the result out to.

So click on PromoTestViewController.xib, bring up the Object library by selecting the third tab in the View toolbar (Utilities) and selecting the third tab in the library toolbar (Object library), as shown in the screenshot below.

Object Library in Xcode 4

From the Object library, drag a UILabel, UITextField, UITextView into the main view. Double click the UILabel and change the text to read “Enter promo code:”. Then double click the text view and delete all the text inside, and optionally change the background color of the UITextField to clear in the Attributes Inspector.

You also may find it useful to go to Editor\Canvas\Show Bounds Rectangles so you can see the bounds of the text view.

At this point your layout should look similar to the screenshot below:

Interface Builder Layout in Xcode 4

Next, you need to set the File’s Owner as the Text Field’s delegate so you can get a callback when the return button is clicked on the keyboard. To do this, control-click on the Text Field, and drag a line from the delegate entry to the File’s Owner.

Also, you need to connect the text view to an outlet so you can set it later. To do this in the cool new Xcode 4 way, first turn on the Assistant Editor (the second button in the Editor tab) and make it show up on the bottom with View\Assistant Layout\Assistant Editors on Bottom. Make sure it’s set to Automatic and that PromoTestViewController.h is visible.

Then select the Text View and control-drag a line from the text view down to right above the @end keyword, set Connection tou Outlet, the Name to textView, and click Connect, as you can see in the screenshot below.

Connecting an Outlet with the Assistant Editor in Xcode 4

At this point Xcode will automatically create a textView property and instance variable for you.

Finally, open PromoTestViewController.h and mark the class as implenting UITextFieldDelegate as follows:

@interface PromoTestViewController : UIViewController <UITextFieldDelegate> {

Then switch to PromoTestViewController.m and implement textFieldShouldReturn as follows:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"Want to redeem: %@", textField.text);
    return TRUE;
}

Compile and run your app, tap the text field, enter a code, and tap the return button, and you should see a message in your console output similar to the following:

2011-03-28 15:37:05.342 PromoTest[44350:207] Want to redeem: test

OK – all the setup is done, and you’re ready to start communicating with the web service!

Communicating with the Web Service

If you’ve grabbed the starter project and skipped ahead, here’s where you should pick back up! Otherwise, good progress so far DIYer! :]

To redeem the promo code, we need to to send a POST to our web service’s with three parameters: the app id, the code to redeem, and the device ID.

The good news is sending a POST is extremely easy with ASIHTTPRequest. You simply:

  • Create a new instance of ASIFormDataRequest and specify the URL
  • Use the setPostValue method to specify each parameter
  • Set the view controller as the delegate of the request, and then call startAsynchronous to start the request in the background
  • When it’s done, either requestFinished or requestFailed will be called on the view controller
  • requestFinished will be called even if the web server responds with an error code. So there you need to check for success or failure…
  • And if success, parse the response string as JSON!

Let’s see what this looks like. First add the following imports to the top of the file:

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "JSON.h"

Then replace textFieldShouldReturn with the following:

- (
            
           

相關推薦

IOS 呼叫WebService 同步和非同步

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

iOS使用WSDL2ObjC工具呼叫Webservice介面

1. 下載 WSDL2ObjC.app https://code.google.com/archive/p/wsdl2objc/downloads 2:下載WSDL檔案 2.1一般情況下, 你會得到這樣的地址 http://pc.cloudhvacr.com/D

ios直接呼叫webService介面的那些坑

              Web Service基本概念 Web Service也叫XML Web Service WebService,是一種可以接收從Internet或者Intranet上的其它系統中傳遞過來的請求,輕量級的獨立的通訊技術。是:通過SOAP在Web上提

IOS如何呼叫WebService?

這是一個老外寫的,我覺得不錯,特地轉過來,而且裡面的英語也不是很難,所以就不翻譯了,順便我也收藏一下,呵呵。 As an iOS developer, you often need to use a web service from your app. S

JBoss呼叫Webservice出現org.jboss.ws.core.jaxws.spi.ProviderImple not found錯誤

一、環境介紹 Linux CentOS 6.5 64bit,JDK1.7 ,JBoss 4.3.0-GA,專案工程引用cxf框架,版本號為2.5.0 二、報錯資訊 專案中自身釋出的Webservice沒有問題,外部可以正常呼叫,但專案作為客戶端呼叫其他系統釋出的Webservic

java根據WSDL文件,如何呼叫WebService

作為一個java開發人員,當我們獲取到了對方提供的wsdl地址,然後在網頁上能夠訪問wsdl文件以後,如何呼叫對方的webservic藉口呢? 一下有幾種方法,可以參考一下。 第一種是      HttpURLConnection方式 第二種是 &n

iOS 呼叫系統傳送郵件

第一步 匯入messageUI.framework框架 第二步 匯入標頭檔案 #import <MessageUI/MessageUI.h> 第三步 @property (nonatomic,strong)  MFMailComposeViewCon

使用axis呼叫webservice時,服務端接收到的引數為null

通過axis呼叫,需要注意兩點: 1)在call.setOperationName是必須通過Qname來制定namespaceURI 2)在設定引數時,不使用服務端定義的引數名,而是arg0~argN來定義,也不需制定namespaceURI,上述程式碼 call.addParamete

java呼叫webservice與介面方法

摘要: 本文講的是java呼叫webservice與介面方法, webservice的呼叫,常用的大約有3種方式:     1、使用axis呼叫     2、使用xfire呼叫     3

呼叫webservice 中出現的問題

寫完webservice當然要呼叫,但是以前呼叫的都是我們的架構封裝好的方法,我自己也沒有看過,換了一家公司以後,自己又寫了一個介面,這時候隊友跪了,該如何呼叫呢?網上找了許多東西,但真正能用的東西不多,好多沒用的東西還可能會誤導大家,現在寫一下我們自己的構成,可能和你的有很多的不一樣,然後即使不同

利用axis呼叫webservice介面

一.首先把wsdl檔案放入eclipse中某個專案中的src目錄下 二.右鍵彈出webservice,然後點選webservice選單,選中genernator client ,選擇axis生成Java檔案 三,然後呼叫. 呼叫說明(其中一種的呼叫方式): DHSFServiceLocator s

eclipse呼叫webservice介面,自動獲取程式碼

使用eclipse呼叫webservice介面自動生成程式碼 第一步:導包 第二步:點選專案-右鍵-new-other-搜尋web service client 第三步:點選web service client-輸入地址 第三步:點選ne

JAVA呼叫webService SOAP12

package com.ess.pos.info.impl; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream;    import org.ap

ios呼叫openvpn過程與出現的問題

必要條件 1 開發者賬號,付費的那種 2 真機除錯 tips:如果不達到條件,會報一定的錯誤,但是錯誤並不能明確指向真正的問題,因此需要注意。 過程 參考:https://www.jianshu.com/p/66039ea97656 一. 建立NetWork

關於iOS呼叫SOAP協議的WebServices介面

在我們做專案的時候,往往移動客戶端是現有平臺的一個擴充套件,因此客戶端實現往受限於服務採用的技術。那麼目前大多數在一個新專案開始的時候,可能會考慮如果要考慮移動客戶端的話會提供介面,但是,有些時候服務端已經有介面,而且這個介面可能不僅僅是提供給移動平臺使用的,比如它的實現採用的是SOAP協議的Web

使用axis呼叫webservice介面

package msdev.yd.interfaceRequest; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.rpc.ParameterMode; import org.apache.ax

ajax 呼叫webservice 跨域問題

                                            &

js呼叫Webservice介面案例

第一步:新建Webservice介面 主檔案方法 using System;using System.Collections.Generic;using System.Web;using System.Web.Services; namespace TestWebApplication{ /// <

Unity3d搭建與呼叫webservice方法

1、在unity安裝目錄下進入F:\Unity5.2.2\Unity\Editor\Data\Mono\lib\mono\2.0,在這個目錄中找到兩個dll分別為system.web.dll、system.web.services.dll,將這兩個dll檔案拖拽進入unity中的Plugins資料夾

C# 呼叫WebService的3種方式 :直接呼叫、根據wsdl生成webservice的.cs檔案及生成dll呼叫、動態呼叫

1.直接呼叫 已知webservice路徑,則可以直接 新增服務引用--高階--新增web引用 直接輸入webservice URL。這個比較常見也很簡單 即有完整的webservice檔案目錄如下圖所示, 也可以在本地IIS根據webservice檔案目錄新發佈一個webserv