Ios-development-with-swift2-accessing-web-services

提供:Dev Guides
移動先:案内検索

Webサービスへのアクセス

アプリケーションでは、APIに接続し、そのAPIからデータを取得してアプリケーションで使用する必要がある場合があります。

まず、データを提供するURLが必要です。

api.openweathermap.org/data/2.5/forecast?id=524901&APPID=1111111111

その後、サービスがhttpsでない場合、アプリケーションがWebサービスと通信できるようにトランスポートレイヤーセキュリティ例外を追加する必要があります。 これらの変更は、 info.plist ファイルで行います。

最後に、URLSessionを作成してネットワーク要求を作成します。

let urlString = URL(string: "your URL") //Making the URL
if let url = urlString {
   let task = URLSession.shared.dataTask(with: url) {
      (data, response, error) in//Creating the URL Session.
      if error != nil {
        //Checking if error exist.
         print(error)
      } else {
         if let usableData = data {
           //Checking if data exist.
            print(usableData)
           //printing Data.
         }
      }
   }
}
task.resume()

これは、URLセッションを使用してアプリケーションでWebサービスを使用する方法です。

アラモファイア

Alamofireは、迅速に記述されたHTTPネットワークライブラリです。 URLリクエストの作成、データの送信、データの受信、ファイルのアップロード、データ、認証、検証などに使用できます。

Aalmofireをインストールするには、https://github.com/Alamofire/Alamofire#installation [GitHub]で公式にAlamofireにアクセスし、インストールガイドを読むことができます。

Alamofireでリクエストを行う

Alamofireでリクエストを行うには、次のコマンドを使用する必要があります。

Import Alamofire
Alamofire.request("url");

応答処理

次のコマンドは、応答処理に使用されます。

Alamofire.request("url").responseJSON {
   response in
   print(response.request)
  //original URL request
   print(response.response)
  //HTTP URL response
   print(response.data)
  //server data
   print(response.result)
  //result of response serialization
   if let JSON = response.result.value {
      print("JSON: \(JSON)")
   }
}

応答検証

次のコマンドは、応答処理に使用されます。

Alamofire.request("https://httpbin.org/get").validate().responseJSON {
   response in
   switch response.result {
      case .success:
      print("Validation Successful")
      case .failure(let error):
      print(error)
   }
}

これらは、URLセッションとAlamofireを使用したURLリクエストの基本です。 より高度なAlamofireについては、https://github.com/Alamofire/Alamofire [Alamofire Documentation]にアクセスしてください。詳しくはこちらをご覧ください。