티스토리 뷰

Swift

[Swift] http basic auth

hyeonii_12 2020. 5. 11. 19:43
반응형

let url = URL(string: "http://localhost:8080/test")

var request = URLRequest(url: url!)

request.httpMethod = "POST"

let id = "hyeoni"
let password = "swift"
let temp = "\(id):\(password)"
let encoded = temp.data(using: .utf8)!.base64EncodedString()
request.setValue("Basic \(encoded)", forHTTPHeaderField: "Authorization")

URLSession.shared.dataTask(with: request) { (data, response, error) in
    DispatchQueue.main.async() {
        do {
            let object = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
            guard let jsonObject = object else { return }
            print(jsonObject)
        } catch {
            print("error")
        }
    }
}.resume()
반응형
댓글