ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Alamofire 이용한 Server 통신
    iOS/개념정리 2022. 1. 24. 16:07

    1. Alamofire란

    - Http 통신을 하기 위한 대표적인 오픈소스 라이브러리이다.

     

    2. Alamofire 설치

    Alamofire는 CocoaPods을 이용하면 쉽게 설치가 가능하다.

     

    2-1. CocoaPods 설치

     

    2-1-1. CocoaPods 이란

       CocoaPods는 Swift 및 Objective-C Cocoa 프로젝트의 종속성 관리자 입니다. 즉, 프로젝트에 필요한 라이브러리를 CocoaPod을       통해 쉽게 관리하고 사용할 수 있습니다.

     

    2-1-2. CocoaPods 설치

       터미널 실행 후

    $ sudo gem install cocoapods 

    터미널에서  프로젝트 폴더로 이동 후 

    $ pod init

    해당 명령어 실행후 Podfile이 생성 되었는지 확인한다.

    Podfile 생성

    아래 Podfile 안에 내용에 실행할 명령어를 입력

    Podfile 내용

    입력후 아래 명령어로 실행.

    $ pod install

    2-2. Alamofire 설치

     

    터미널에서 설치 하고싶은 프로젝트로 이동한 다음에 위의 과정을 보고 podfile을 생성한다.

    podfile

    podfile을 위와 같이 수정후에 pod install을 진행한다.

     

    pod 설치를 완료했으면

    .xcworkspace 파일을 이용하여 프로젝트를 다시 시작한다.

     

    3. Alamofire 사용하기

     

    - json data 를 서버에서 받아서 let data 에 넣어줌

    - 넣어준 데이터는 다시 bookData.items에 넣어줌

    import Foundation
    import Alamofire
    
    class ApiClient{
        //urlString으로 alamofire api 를 사용해서 response를 받기
        func protocolWithAlamo(urlString: String, whenFailed: @escaping () -> Void ,completition: @escaping ([Items]?) -> Void) {
            //위의 URL와 파라미터를 담아서 POST 방식으로 통신하며, statusCode가 200번대(정상적인 통신) 인지 유효성 검사 진행
            let alamo = AF.request(urlString, method: .get, parameters: nil).validate(statusCode: 200..<300)
            let decoder = JSONDecoder()
            
            //결과값으로 문자열을 받을 때 사용
            alamo.responseString() { response in
                switch response.result
                {
                //통신성공
                case .success(let value):
                    let data: Data = Data(value.utf8)
                    if let bookData = try? decoder.decode(Books.self, from: data){
                    //escaping으로 통신이 완료 되었을때 bookData.items를 반환
                        completition(bookData.items)
                    }else{
                        whenFailed()
                    }
                //통신실패
                case .failure(let error):
                    print("error: \(String(describing: error.errorDescription))")
                    whenFailed()
                }
            }
        }
    
    }

    'iOS > 개념정리' 카테고리의 다른 글

    <Swift> Delegate  (1) 2022.01.25
    <Swift> Firebase 연동  (0) 2022.01.25
    txt 파일 json 파싱하기  (0) 2022.01.24
    Swift MVVM 패턴  (0) 2022.01.21
    프로젝트 생성(storyboard 아닌 xib 사용)  (1) 2022.01.21

    댓글

Designed by Tistory.