61
51

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 3 years have passed since last update.

URLsessionを用いたHTTPリクエストの方法(Swift, Xcode)

Last updated at Posted at 2020-05-21

#はじめに
APIKitやAlamofireなどのライブラリを使わず標準のURLsessionを用いたHTTPリクエストを実行するを簡単にまとめました。

##1. URLsession手順

  1. URLを生成
  2. URLRequestを生成
  3. 必要なパラメーターを付与
  4. 通信を行う
  5. レスポンスで受け取ったdata, response, errorの処理を行う

##2.基本のコード

###Get
基本は以下のコードのようになります。

let url = URL(string: "https://hogehoge.hoge")!  //URLを生成
var request = URLRequest(url: url)               //Requestを生成
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in  //非同期で通信を行う
    guard let data = data else { return }
    do {
        let object = try JSONSerialization.jsonObject(with: data, options: [])  // DataをJsonに変換
        print(object)
    } catch let error {
        print(error)
    }
}
task.resume()

###Post, Put
PostやPutにしたい場合はrequest.httpMethodを使います。

let url = URL(string: "https://hogehoge.hoge")! 
var request = URLRequest(url: url)
request.httpMethod = "POST"      // Postリクエストを送る(このコードがないとGetリクエストになる) 
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in  
    guard let data = data else { return }
    do {
        let object = try JSONSerialization.jsonObject(with: data, options: [])
        print(object)
    } catch let error {
        print(error)
    }
}
task.resume()

##3. Body, Header, Queryを付与したいときのコード
Bodyを付与(Get)

let url = URL(string: "https://hogehoge.hoge")! 
var request = URLRequest(url: url)
request.httpBody = "email=hoge@hoge.com&username=hogehoge".data(using: .utf8)  // 例)emailとpasswordを付与する場合

Headerを付与(Get)

let url = URL(string: "https://hogehoge.hoge")! 
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")  //jsonでヘッダーに付与
request.allHTTPHeaderFields = ["Token": "snsjetnglsdfnm"]                 // 例) ヘッダーにトークンを付与する場合

Queryを付与(Get)

var urlComponents = URLComponents(string: "https://hogehoge.hoge")!  //URLComponentsでURLを生成
urlComponents.queryItems = [
    URLQueryItem(name: "email", value: "hoge@hoge.com"),      // 例) emailとpasswordを付与
    URLQueryItem(name: "username", value: "hogehoge")         //クエリを追加したければ、ここに書いていく
]
var request = URLRequest(url: urlComponents.url!)

 生成されるリクエスト "https://hogehoge.hoge?email=hoge@hoge.com&username=hogehoge"

##参考
下記のサイトを見ながら実装したので詳細はこちらをご確認ください。

URLSessionを用いた通信 - GitHub
HTTP GETとPOST(Swift)
【Swift】URLSessionまとめ

61
51
1

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
61
51

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?