[SWIFT] Alamofire를 사용하여 서버와 통신하기
먼저 Alamofire 라이브러리를 설치해야 하기때문에 podfile에 들어간다.
# Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'testApp' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! pod 'Alamofire' ,'~> 4.7' <<< 추가 # Pods for testApp end |
pod 'Alamofire' ,'~> 4.7'를 추가해 주고 터미널로 간다.
pod install |
pod install 로 설치를 해준다.
이제 Alamofire를 사용할 controller에 가서
import Alamofire |
를 추가시켜준다. 그러면 준비는 끝났다.
나는 주로 get 방식과 post 방식을 사용하는데 데이터를 보낼때는 post, 받아야할 데이터가 있을때는 get방식을 사용한다.
먼저 get방식 사용법이다.
[get]
Alamofire.request(url, method: .get, encoding: JSONEncoding.default, headers: [:]).responseJSON { response in . . 코드 작성 . } |
url에는 데이터를 요청하고자 하는 url
method에는 어떤 방식으로 사용할 것인지(예: .post, .get 등등...)
encoding에는 인코딩 타입
header에는 [:] 형식으로 적으면 된다.
예를들어 Content-Type:application/json;charset=utf-8 을 헤더로 하고싶다면
["Content-Type":"application/json;charset=utf-8"] 로 작성해서 넣으면 된다.
여기에 쿠키값도 넣고싶다면 ["Content-Type":"application/json;charset=utf-8","Cookie":쿠키값] 이렇게 작성할 수 있다.
받는건 response형식은 json 으로 받고 (string으로 받으려면 responseString) 처리 해 주면된다.
post 방식은 여기에 parameters만 추가 시켜주면 된다. 타입은 Parameters 타입으로!
[post]
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: [:]).responseJSON { response in . .코드 작성 . } |
뭔가 하나라도 꼬이면 method 에서 오류가 발생하니 꼼꼼하게 잘 작성하면 된다!