AlamofireでBASIC認証した
Swiftで書かれたHTTP通信ライブラリのAlamofireを使ってBASIC認証したメモ。
https://github.com/Alamofire/Alamofire#http-basic-authentication に使用方法が書かれている。
CocoaPodsを利用してインストールした。
Podfileに以下のように記載して pod install
する。
pod 'Alamofire', '~> 1.3.0'
ViewController.swift
などの使用したいファイルの先頭でインポートする。
import UIKit
の下などに書くと良い。
Alamofireのインポート
import Alamofire
BASIC認証
// TextFieldから値を取得 let user = usernameTextField.text let password = passwordTextField.text // 値をセットしてBASIC認証 Alamofire.request(.GET, "http://localhost:3000/api/basic-auth.json") .authenticate(user: user, password: password) .response { (request, response, data, error) -> Void in if response?.statusCode == 200 { println("200 OK !!!") } else { println("401 Unauthorized !!!") } }
関係ないけど、 .authenticate
のテストどんな感じなんだろーと思って
Tests/AuthenticationTests.swift
を覗いていたらhttpbin(1): HTTP Client Testing Service という便利そうなものを見つけた。
HTTP通信のテストする時とかに活用できそう。