iOS アプリケーションからのリソース要求

improve this page | report issue

概説

MobileFirst アプリケーションは WLResourceRequest REST API を使用してリソースにアクセスできます。
REST API は、すべてのアダプターおよび外部リソースで機能します。

前提条件:

WLResourceRequest

WLResourceRequest クラスは、アダプターまたは外部リソースに対するリソース要求を処理します。

WLResourceRequest オブジェクトを作成し、リソースへのパスと HTTP メソッドを指定します。
使用可能なメソッドは、WLHttpMethodGetWLHttpMethodPostWLHttpMethodPut、および WLHttpMethodDelete です。

Objective-C

WLResourceRequest *request = [WLResourceRequest requestWithURL:[NSURL URLWithString:@"/adapters/JavaAdapter/users/"] method:WLHttpMethodGet];

Swift

let request = WLResourceRequestSwift(
    URL: URL(string: "/adapters/JavaAdapter/users"),
    method: WLResourceRequestSwift.WLHttpMethodGet
)
  • JavaScript アダプター の場合は、/adapters/{AdapterName}/{procedureName} を使用します。
  • Java アダプターの場合は、/adapters/{AdapterName}/{path} を使用します。 path は、Java コードで @Path アノテーションをどのように定義したかによって決まります。 これには、使用した @PathParam も含まれます。
  • プロジェクトの外部にあるリソースにアクセスするには、外部サーバーの要件のとおりに完全な URL を使用してください。
  • タイムアウト: オプション。ミリ秒単位の要求タイムアウトです。

要求の送信

sendWithCompletionHandler メソッドを使用して、リソースを要求します。
取得したデータを処理するには、完了ハンドラーを指定します。

Objective-C

[request sendWithCompletionHandler:^(WLResponse *response, NSError *error) {
    if (error == nil){
        NSLog(@"%@", response.responseText);
    } else {
        NSLog(@"%@", error.description);
    }
}];

Swift

request.send() {(response, error) in
    if (error != nil){
        print("Failure: " , error!);
    }
    else if (response != nil){
        print("Success: " + response!.responseText);
    }
}

代替方法として、sendWithDelegate を使用して、NSURLConnectionDataDelegateNSURLConnectionDelegate の両方のプロトコルに準拠するデリゲートを指定することができます。 これにより、バイナリー応答の処理など、よりきめ細かに応答を処理できます。

パラメーター

要求を送信する前に、必要に応じてパラメーターを追加したい場合があります。

パス・パラメーター

上記の説明のとおり、path パラメーター (/path/value1/value2) は、WLResourceRequest オブジェクトの作成中に設定されます。

照会パラメーター

query パラメーター (/path?param1=value1...) を送信するには、パラメーターごとに setQueryParameter メソッドを使用します。

Objective-C

[request setQueryParameterValue:@"value1" forName:@"param1"];
[request setQueryParameterValue:@"value2" forName:@"param2"];

Swift

request.setQueryParameterValue("value1", forName: "param1")
request.setQueryParameterValue("value2", forName: "param2")

JavaScript アダプター

JavaScript アダプターは、名前のない順序付きのパラメーターを使用します。 パラメーターを JavaScript アダプターに渡すには、以下のように名前 params を使用してパラメーターの配列を設定します。

Objective-C

[request setQueryParameterValue:@"['value1', 'value2']" forName:@"params"];

Swift

request.setQueryParameterValue("['value1', 'value2']", forName: "params")

これは、WLHttpMethodGet と一緒に使用してください。

フォーム・パラメーター

本体内の form パラメーターを送信するには、sendWithCompletionHandler ではなく、sendWithFormParameters を使用します。

Objective-C

//@FormParam("height")
NSDictionary *formParams = @{@"height":@"175"};

//Sending the request with Form parameters
[request sendWithFormParameters:formParams completionHandler:^(WLResponse *response, NSError *error) {
    if (error == nil){
        NSLog(@"%@", response.responseText);
    } else {
        NSLog(@"%@", error.description);
    }
}];

Swift

//@FormParam("height")
let formParams = ["height":"175"]

//Sending the request with Form parameters
request.send(withFormParameters: formParams) {(response, error) in
    if (error != nil){
        print("Failure: " , error!);
    }
    else if (response != nil){
        print("Success: " + response!.responseText);
    }
}

JavaScript アダプター

JavaScript アダプターは、名前のない順序付きのパラメーターを使用します。 パラメーターを JavaScript アダプターに渡すには、以下のように名前 params を使用してパラメーターの配列を設定します。

Objective-C

NSDictionary *formParams = @{@"params":@"['value1', 'value2']"};

Swift

let formParams = ["params":"['value1', 'value2']"]

これは、WLHttpMethodPost と一緒に使用してください。

ヘッダー・パラメーター

HTTP ヘッダーとしてパラメーターを送信するには、setHeaderValue API を使用します。

Objective-C

//@HeaderParam("Date")
[request setHeaderValue:@"2015-06-06" forName:@"birthdate"];

Swift

//@HeaderParam("Date")
request.setHeaderValue("2015-06-06", forName: "birthdate")

その他のカスタム本体パラメーター

  • sendWithBody を使用して、本体に任意のストリングを設定できます。
  • sendWithJSON を使用して、本体に任意のディクショナリーを設定できます。
  • sendWithData を使用して、本体に任意の NSData を設定できます。

completionHandler およびデリゲートのためのコールバック・キュー

応答の受信中に UI がブロックされるのを回避するには、API の sendWithCompletionHandler セットおよび sendWithDelegate セットに対して completionHandler ブロックまたはデリゲートを実行するプライベート・コールバック・キューを指定します。

Objective-C

//creating callback queue
dispatch_queue_t completionQueue = dispatch_queue_create("com.ibm.mfp.app.callbackQueue", DISPATCH_QUEUE_SERIAL);

//Sending the request with callback queue
[request sendWithCompletionHandler:completionQueue completionHandler:^(WLResponse *response, NSError *error) {
    if (error == nil){
        NSLog(@"%@", response.responseText);
    } else {
        NSLog(@"%@", error.description);
    }
}];

Swift

//creating callback queue
let completionQueue = DispatchQueue(label: "com.ibm.mfp.app.callbackQueue");

//Sending the request with callback queue
request.send(withQueue: queue){ (response, error) in
    if (error != nil){
        print("Failure: " , error!);
    }
    else if (response != nil){
        print("Success: " + response!.responseText);
    }
}

応答

response オブジェクトには応答データが含まれており、そのメソッドとプロパティーを使用して必要な情報を取得することができます。 よく使用されるプロパティーは、responseText (ストリング)、responseJSON (ディクショナリー) (応答が JSON の場合)、および status (整数) (応答の HTTP 状況) です。

response オブジェクトおよび error オブジェクトを使用して、アダプターから取り出されたデータを取得します。

外部マイクロサービスにアクセスするための WLResourceRequest の使用

WLResourceRequest API を使用して、Mobile Foundation の外側でホストされているマイクロサービスにモバイル・アプリがアクセスできるようにすることができます。Mobile Foundation によって、アダプターを使用せずに Mobile Foundation API Connector を介してマイクロサービスまたはエンタープライズ・バックエンド・サービスにセキュアな呼び出しを行うことができます。API Connector は、アダプターと同様に、Mobile Foundation の OAuth 2.0 メカニズムに基づいて確実にセキュアな呼び出しを行うことができるようにします。API Connector を使用すると、Mobile Foundation 管理者は Mobile Foundation でマイクロサービスまたはエンタープライズ・バックエンド・サービスの詳細を構成およびデプロイできます。Mobile Foundation ランタイムはデプロイされた構成を使用して、モバイル・アプリからマイクロサービスまたはバックエンド・サービス要求をセキュアに呼び出します。

Mobile Foundation API Connector の構成を参照してください。

マイクロサービス URL (http://mybluemix.net/resorts/cities など) にアクセスするには、Mobile Foundation ランタイム・バックエンド・サービスを次のように構成します。

{
  "service": "resorts",
  "baseUrl":"http://mybluemix.net/resorts"
}

WLResourceRequest は次のように定義できます。

Objective-C

WLResourceRequest *request = [WLResourceRequest requestWithURL:[NSURL URLWithString@"url"] method:WLHttpMethodGet backendServiceName timeout];

Swift

let request = WLResourceRequestSwift(
    url: URL(),
    method: WLResourceRequestSwift.WLHttpMethodGet,
    backendServiceName: ,
    timeout
)
  • url : マイクロサービス・エンドポイントの相対 URL。例: cities
  • method : 使用する HTTP メソッド。例: WLResourceRequest.GET
  • backendServiceName : データのフェッチ元となるサーバー上で構成されたバックエンド・サービスの名前。例: resorts
  • timeout : この要求のタイムアウト時間 (ミリ秒単位)。

Objective-C

WLResourceRequest* request = [WLResourceRequest requestWithURL:@"cities" method:WLHttpMethodGet backendServiceName:@"resorts" timeout:3000]

Swift

let request = WLResourceRequestSwift(
    url: URL(string: "/cities"),
    method: WLResourceRequestSwift.WLHttpMethodGet,
    backendServiceName: "resorts" ,
    timeout: 3000
)

詳細情報

WLResourceRequest について詳しくは、API リファレンスを参照してください

サンプル・アプリケーションのイメージ

サンプル・アプリケーション

ResourceRequestSwift プロジェクトには、Swift で実装され、Java アダプターを使用してリソース要求を行う iOS アプリケーションが含まれています。
アダプター Maven プロジェクトには、リソース要求呼び出し中に使用される Java アダプターが含まれています。

ここをクリック して iOS プロジェクトをダウンロードします。
ここをクリック してアダプター Maven プロジェクトをダウンロードします。

サンプルの使用法

サンプルの README.md ファイルの指示に従ってください。

iOS 9 についての注意:

Xcode 7 を使用すると、デフォルトで Application Transport Security (ATS) が使用可能になります。 チュートリアルを実行するには、ATS を使用不可にしてください (続きを読む)。

  1. Xcode で、右クリックにより「[プロジェクト]/info.plist ファイル」→「指定して開く」→「ソース・コード」を選択します。
  2. 以下を貼り付けます。
     <key>NSAppTransportSecurity</key>
     <dict>
           <key>NSAllowsArbitraryLoads</key>
           <true/>
     </dict>
Inclusive terminology note: The Mobile First Platform team is making changes to support the IBM® initiative to replace racially biased and other discriminatory language in our code and content with more inclusive language. While IBM values the use of inclusive language, terms that are outside of IBM's direct influence are sometimes required for the sake of maintaining user understanding. As other industry leaders join IBM in embracing the use of inclusive language, IBM will continue to update the documentation to reflect those changes.
Last modified on June 17, 2020