-
iOS [Swift] - Alamofire 통신iOS Develop 2022. 3. 9. 17:19반응형
Swift에서 http 통신을 하기 위한 방법에는 대표적으로 2가지가 있다.
[URLSession / Alamofire]
오늘은 그 중 URLSession 기반으로, 보다 데이터 접근을 편리하게 해주며 코드 간편화를 통해 가독성까지 높일 수 있는 'Alamofire'에 대해 작성해보겠다!! :-)
Alamofire
- http 네트워킹 라이브러리 (자주 사용되는 코드를 편리하게 사용할 수 있도록 도움)
- REST API 통신 지원
Alamofire 사용 순서
- Mac Terminal에서 'cocoapods'를 설치해준다.
" sudo gem install cocoapods "
(자세한 과정은 https://guides.cocoapods.org/using/getting-started.html 을 통해 확인!) - 열려있는 Xcode Project를 종료한다.
- Terminal에서 (진행 중인 Xcode Project 경로) pod init 을 통해 Podfile을 생성해준다.
- Podfile에 Alamofire 라이브러리를 추가해준다.
※ Finder에서 Podfile을 직접 열고 저장해도 되고, Terminal에서 sudo vi로 편집해줘도 된다.
(자세한 과정은 https://github.com/Alamofire/Alamofire 을 통해 확인!) - Podfile에 라이브러리를 추가하고 저장까지 마쳤다면, Terminal 같은 경로에서 pod install 을 하여
Project에 Alamofire 라이브러리를 설치시켜준다. - 이와 같은 과정을 모두 마쳤다면, Project 경로에는 "프로젝트명".xcworkspace 라는 파일이 생성되었을 것이다.
이제는 이 파일을 open하여 사용한다. - 네트워크 통신을 할 swift 파일에서 import Alamofire 를 하여 관련 함수들을 사용하여 통신 코드를 작성한다.
JSON Data 가져오기
import Alamofire import Foundation class ApiClient { func connectJsonData(productByTotalCompletion: @escaping ([Detail_InfoList]?) -> Void, productByCategoryCompletion: @escaping (ProductModel?) -> Void, categoryCompletion: @escaping ([String]) -> Void) { let stringURL = "url 주소 입력" /// get 메소드를 통해 json 데이터 가져옴 let connection = AF.request(stringURL, method: .get, parameters: nil).validate(statusCode: 200..<300) connection.responseString { response in switch response.result { /// 통신 결과에 따라 성공 / 실패의 경우 코드 작성 case .success(let value): let data = value.data(using: .utf8) let decoder = JSONDecoder() /// Model에 맞게 decode 해준 후, 진행 코드 작성 if let data = data, let jsonData = try? decoder.decode(ProductModel.self, from: data) { // .. code 작성 } case .failure(let err): print("실패 에러 \(err)") } } } }통신 결과로 얻은 데이터는 Closure를 통해 호출부에서 넘겨받아 후처리를 해준다!! :)
'iOS Develop' 카테고리의 다른 글
iOS [Swift] - WatchOS HealthKit Background (0) 2022.03.23 iOS [Swift] - WatchOS 화면 Push & 값 전달하기 (0) 2022.03.21 iOS [Swift] - NotificationCenter 사용하기 (0) 2022.03.20 iOS [Swift] - Toast Message (0) 2022.03.17 iOS [Swift] - Delegate Pattern (델리게이트 패턴) (0) 2022.03.09