0. Alamofire란?
- Swift에서 HTTP 네트웍 라이브러리를 사용해 만든 것이다.
1. 사용 가능한 환경
-
IOS 10.0+ (현재 2020.11.07 기준)
-
아래의 주소에서 최신 정보를 확인할 수 있다.
Alamofire/Alamofire
Elegant HTTP Networking in Swift. Contribute to Alamofire/Alamofire development by creating an account on GitHub.
github.com
2. 설치
- CocoaPods을 이용해 추가한다.
pod 'Alamofire', '~> 5.2'
3-1. 사용 하기 전 기존 코드(network 라이브러리 사용 시)
import Foundation
import Network
class LoginManager {
static let shared = LoginManager()
private init() {}
private let githubClientId = ""
private let githubClientSecret = ""
func requestCodeToGithub() {
let scope = "repo,user"
let urlString = "https://github.com/login/oauth/authorize?client_id=\(githubClientId)&scope=\(scope)"
if let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
}
func requestAccessTokenToGithub(with code: String) {
guard let url = URL(string: "https://github.com/login/oauth/access_token") else {return}
let session = URLSession.shared
let parameters = ["client_id": githubClientId,
"client_secret": githubClientSecret,
"code": code]
var request = URLRequest(url: url)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
guard let json = try! JSONSerialization.jsonObject(with: data) as? [String: Any] else {
print(String(data: data, encoding: .utf8) ?? "Not string?!?")
return
}
// json["access_token"] access_token 값
self.getUser(accessToken: json["access_token"] as! String)
})
task.resume()
}
func getUser(accessToken: String) {
guard let url = URL(string: "https://api.github.com/user") else {return}
let session = URLSession.shared
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.addValue("token \(accessToken)", forHTTPHeaderField: "Authorization")
request.addValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
guard let json = try! JSONSerialization.jsonObject(with: data) as? [String: Any] else {
print(String(data: data, encoding: .utf8) ?? "Not string?!?")
return
}
// 프로필 사진 주소
print(json["avatar_url"] as! String)
// 이름 가져오기
print(json["name"] as! String)
})
task.resume()
}
func logout() {
}
}
3-2. Alamofire를 적용 한 후 코드
import Foundation
import Alamofire
class LoginManager {
static let shared = LoginManager()
private init() {}
private let githubClientId = ""
private let githubClientSecret = ""
func requestCodeToGithub() {
let scope = "repo,user"
let urlString = "https://github.com/login/oauth/authorize?client_id=\(githubClientId)&scope=\(scope)"
if let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url)
}
}
func requestAccessTokenToGithub(with code: String) {
let url = "https://github.com/login/oauth/access_token"
let headers: HTTPHeaders = ["Accept" : "application/json"]
let parameters = ["client_id": githubClientId,
"client_secret": githubClientSecret,
"code": code]
AF.request(url, method: .post, parameters: parameters, headers: headers).responseJSON(){
response in
switch response.result {
case .success:
if let jsonObject = try! response.result.get() as? [String: Any] {
if let accessToken = jsonObject["access_token"] as? String {
self.getUser(accessToken: accessToken)
}
}
case .failure(let error):
print(error)
return
}
}
}
func getUser(accessToken: String) {
let url = "https://api.github.com/user"
let headers: HTTPHeaders = ["Authorization" : "token \(accessToken)"]
AF.request(url, headers: headers).responseJSON(){
response in
switch response.result {
case .success:
var user = User()
if let jsonObject = try! response.result.get() as? [String: Any] {
// 프로필 사진 주소
print(jsonObject["avatar_url"] as! String)
// 이름 가져오기
print(jsonObject["name"] as! String)
}
case .failure(let error):
print(error)
return
}
}
}
func logout() {
}
}
-
해당 코드는 Github Social Login을 구현한 코드이다.
-
requestAccessTokenToGithub와 getUser 함수를 보면 알겠지만 코드가 굉장히 짧아진 것을 확인 할 수 있다.
4. Alamofire API
AF.request("https://httpbin.org/get")
AF.request("https://httpbin.org/post", method: .post)
AF.request("https://httpbin.org/put", method: .put)
AF.request("https://httpbin.org/delete", method: .delete)
-
간단하다. CocoaPods로 설치 후, import Alamofire 를 해준 뒤 위의 4개의 코드로 HTTPMethods를 호출 할 수 있다.
-
method를 작성하지 않으면 기본 값으로 Get이 들어간다는 것을 기억하자.
AF.request("https://httpbin.org/post",
method: .post,
parameters: login,
encoder: JSONParameterEncoder.default).response { response in
debugPrint(response)
}
- request 뒤에 closure로 Collback 받아서 response 값을 얻을 수 있다.
[참고 자료]
- Alamofire Github 주소이다.
Alamofire/Alamofire
Elegant HTTP Networking in Swift. Contribute to Alamofire/Alamofire development by creating an account on GitHub.
github.com
'프로그래밍 > iOS' 카테고리의 다른 글
Threading Programming Guide (1) - 소개 (0) | 2020.12.21 |
---|---|
UICollectionView에 대해 알아보자. (0) | 2020.12.20 |
Github OAuth로 로그인하기 (0) | 2020.12.20 |
구조체(Struct) 클래스(Class)의 공통점과 차이점 (0) | 2020.12.20 |
MVC(Model-View-Controller) 패턴 (0) | 2020.12.20 |