일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- layoutSubviews
- garbage collection
- App Connect
- YGEnums.h
- HIG
- Firebase
- Tuist
- arc
- pagination
- Tuist-Action
- Github-Action
- AppStore
- human interface guidelines
- 회고
- retain cycle
- alamofire
- Automatic Reference Count
- ios
- FlexLayout
- Nan
- UITest
- Xcode
- fetchSignInMethods
- rc
- authentication
- playground
- content-type
- Swift
- SPM
- HealthKit
- Today
- Total
멋있게걷는방법
[Swift] Alamofire 를 쓴다면 꼭 알아야 하는 내용 본문
평소에는 아무 생각 없이 쓰다가 최근에 알게 되어 충격이었던 사실을 적어보려고 합니다.
func example() {
let url = "URL"
let headers : HTTPHeaders = ["Content-Type" : "application/json"]
AF.request(url,
method: .get,
encoding: URLEncoding.queryString,
headers: headers).validate()
.responseData(emptyResponseCodes: [200, 201, 204]) { [weak self] response in
switch response.result {
case .success:
//성공시
case .failure:
//실패시
}
}
}
평소 이렇게 Alamofire 를 사용해 서버 통신을 했는데,
최근에 알게 된 내용은 GET 메서드를 사용할 때에는 Content-Type 이 필요없다는 것과,
Alamofire 에서는 header의 default 값이 ["Content-Type" : "application/json"] 라는 점입니다.
Content-Type
Content-Type 이란 API를 요청할 때 request에 실어 보내는 데이터 타입의 정보입니다.
따라서 Content-Type 은 주로 POST,PUT 메서드와 같이 body에 실어서 보낼 때 사용합니다.
(물론 GET메서드에서도 body 에 데이터를 실어 보낼 때도 있음)
Okay.. 그럼 GET 메서드에서 body에 데이터를 실어 보내지 않으면 Content-Type을 쓸 필요가 없는 건 알겠죠!
Alamofire - Header
Alamofire 에서는 Header를 default로 ["Content-Type" : "application/json"] 입니다.
자세히는 encoding 시 header를 "Content-Type" : "application/json"로 설정해 줍니다.
GET 메서드로 요청할 땐 아래처럼 (body에 데이터가 없는),
encoding: URLEncoding.queryString
body에 데이터를 실어서 보낼 때는 아래처럼 했을 텐데요!
encoding: JSONEncoding.default
코드를 뜯어보면 둘 다 ParameterEncoding 프로토콜을 상속하고 있는 걸 볼 수 있습니다.
그럼 ParameterEncoding 프로토콜을 뜯어보면
encode 함수를 볼 수 있습니다.
마지막으로 encode 함수를 뜯어보면
이렇게! header를 ["Content-Type" : "application/json"]으로 세팅해 주는 걸 볼 수 있습니다.
따라서 처음에 나왔던 코드처럼
func example() {
let url = "URL"
let headers : HTTPHeaders = ["Content-Type" : "application/json"]
AF.request(url,
method: .get,
encoding: URLEncoding.queryString,
headers: headers).validate()
.responseData(emptyResponseCodes: [200, 201, 204]) { [weak self] response in
switch response.result {
case .success:
//성공시
case .failure:
//실패시
}
}
}
이러한 요청을 보내야 한다면, 이렇게 바꿀 수 있습니다.
func example() {
let url = "URL"
AF.request(url,
method: .get,
encoding: URLEncoding.queryString).validate()
.responseData(emptyResponseCodes: [200, 201, 204]) { [weak self] response in
switch response.result {
case .success:
//성공시
case .failure:
//실패시
}
}
}
정리하자면..
1. Body에 데이터를 실어서 서버에 요청하지 않으면 Content-Type 은 필요 없다!
2. Alamofire는 encoding 할 때 header를 ["Content-Type" : "application/json"] 로 세팅해 주기 때문에
따로 헤더에 넣을 게 없다면 쓸 필요가 없다!
'iOS' 카테고리의 다른 글
[Swift] firebase - 이메일 중복 검사 (0) | 2023.04.12 |
---|---|
[UITest] password textFiled 에 tap 이 안 될 때? (0) | 2023.04.04 |
[Swift] HealthKit 설정과 데이터 요청 (distanceWalkingRunning, activeEnergyBurned, appleExerciseTime) (0) | 2023.03.07 |
[Swift] 값이 NaN 으로 변한다구요? (0) | 2023.01.09 |
나의 첫 App Store 심사 회고 (1) | 2022.10.10 |