10
11

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.

【iOS】Basic認証

Posted at

SwiftでBasic認証2種

外部ライブラリ使わない版

// 認証情報
let username = "name"
let password = "pass"
// リクエスト準備
let session = URLSession.shared
guard let url = URL(string: "https://hogehoge.com") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
guard let credentialData = "\(username):\(password)".data(using: String.Encoding.utf8) else { return }
let credential = credentialData.base64EncodedString(options: [])
let basicData = "Basic \(credential)"
request.setValue(basicData, forHTTPHeaderField: "Authorization")
// リクエスト実行
session.dataTask(with: request) { data, urlresponse, error in
  // レスポンス処理
}.resume()

Alamofire版

// 認証情報
let username = "name"
let password = "pass"
// リクエスト準備
guard let url = URL(string: "https://hogehoge.com") else { return }
guard let credentialData = "\(username):\(password)".data(using: String.Encoding.utf8) else { return }
let credential = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Basic \(credential)"]
request(url, method: .post, parameters: nil, headers: headers).response(completionHandler: { defaultDataResponse in 
    // レスポンス処理
}
10
11
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
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?