0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift5で非同期処理を用いたHTTP処理

0
Last updated at Posted at 2019-12-25

はじめに

自分用のメモとして残します。

マエフリ

アプリケーションを実行する上でサーバ通信は欠かせない存在です。
そんな中、クライアントとサーバ間で通信する上でHTTP通信というものがあります。
今回はそのHTTPと非同期処理を組み合わせた記述を紹介します。
※HTTPの仕組みや非同期処理の説明などは知見がある前提です。

コード紹介

Main.swift
//実際に送るJson型のオブジェクト
let params:[String:Any] = [
    "id": "Test",
    "pass": "1234567890"
]
//トリガー
ApiRequest(params: params,url: "URL", { str in
    
    do{
        // パースする
        let items = try JSONSerialization.jsonObject(with: str) as! Dictionary<String, Any>
        //エラーを吐いているかいないか確認
        if items["error_code"] as! Int == 0 {
            //成功処理
           print("成功!!!")
           
        }
        else{
            //失敗時エラー処理
            print("失敗!!!")
            return
        }

    }
    catch{
    }
    
})

//API処理
func ApiRequest(params: [String:Any],url: String, _ after:@escaping (Data) -> ()){
    //受け取りデータ
    var acceptanceTextData: Data!
    
    //WebAPi 指定
    var request = URLRequest(url: URL(string: url)!)

    //ヘッダー設定
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    
    //非同期処理を行う
    let dispatchQueue = DispatchQueue(label: "Dispatch Queue", attributes: [], target: nil)
    
    do{
        request.httpBody = try JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
        let task:URLSessionDataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {(data,response,error) -> Void in
            let resultData = String(data: data!, encoding: .utf8)!
            //Jsonデータをディシリアライズ
            var personalData: Data =  resultData.data(using: String.Encoding.utf8)!
            
            dispatchQueue.async {
                //Dataに格納
                acceptanceTextData = personalData
                //実際に格納処理している
                after(acceptanceTextData)

            }
        })
        task.resume()
        
        
    }catch{
        //ネットワークエラー
        return
    }
}


コード説明

まずAPIサーバと通信する際だいたい、URLの末尾が処理によって変わる為、毎回毎回HTTP処理のメソッドを記述するのは可読性が悪くなってしまいます。
その為、HTTP処理専用のメソッドを作りAPIサーバと通信をしたいときにJSONを使ったPOST処理の場合は上記に記述した構文を使うことができます。

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?