본문 바로가기

라이브러리

iOS HTTP통신 라이브러리 Alamofire 간단한 사용법

이번 포스팅에서는 iOS HTTP 통신을 할 때 필수 라이브러리Alamofire에 대해서 아주 간단한 포스팅을 해보려고 합니다.




iOS에서 기본적으로 제공하고 있는 HTTP통신 방법은 여러가지가 있지만 URLSession을 이용한 방법이 있습니다.




모두같은 방법으로 사용하진 않겠지만 기본적으로 이러한 형태로 요청이 가능합니다.


var request = URLRequest(url: URL(string: "https://api.github.com/users")!)
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { (data, response, error) in
            
}



만약 여기서 Get요청이 POST요청으로 바뀐다고 한다면



var request = URLRequest(url: URL(string: "https://api.github.com/users")!)
request.httpMethod = "POST"
let params = ["id":id, "password":password] as Dictionary
        
do{
        try request.httpBody = JSONSerialization.data(withJSONObject: params, options: [])
 }catch{
        return
 }
        
URLSession.shared.dataTask(with: request) { (data, response, error) in
            
}


이런식으로 파라미터들을 넘길 수 있습니다.



만약에 여기서 Header를 추가하게 된다면



request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

를 또 추가를 해줘야하며



var request = URLRequest(url: URL(string: "https://api.github.com/users")!)
request.httpMethod = "POST"
let params = ["id":id, "password":password] as Dictionary
        
do{
        try request.httpBody = JSONSerialization.data(withJSONObject: params, options: [])
}catch{
        return
}
        
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
        
URLSession.shared.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
        if let response = response as? HTTPURLResponse, 200...299 ~= response.statusCode {
            //SUCCESS
        }else{
            //Failure
        }
})


이렇게 성공, 실패를 또 나눠야합니다.



이런식의 코드는 가독성은 물론이며, 조금의 설정만 바꾸면 많은 것이 변경되어야 해서 여러모로 불편한점이 있습니다.





그래서 이러한 불편한 것들을 개선시키는 라이브러리인 Alamofire에 대해서 잠깐 맛만 보도록 하려고 합니다.




Alamofire는 Swift로 작성된 HTTP 네트워킹 라이브러리입니다.



설치는 CocoaPod으로 진행할 수 있습니다.


source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!

target '<Your Target Name>' do
    pod 'Alamofire', '~> 4.4'
end




이제 설치까지 완료 하였으니 한번 똑같은 URL로 요청해 봅시다.



Alamofire.request("https://api.github.com/users", method: .get, parameters: [:], encoding: URLEncoding.default, headers: ["Content-Type":"application/json", "Accept":"application/json"])
            .validate(statusCode: 200..<300)
            .responseJSON { (response) in
            if let JSON = response.result.value
            {
                print(JSON)
            }
        }



네, 끝입니다.



하나씩 내용을 짚어봅시다.


일단 request메소드의 변수들을 봅시다.

 request메소드를 Command + Mouse Left를 클릭해 정보를 보면


request(

    _ url: URLConvertible,

    method: HTTPMethod = .get,

    parameters: Parameters? = nil,

    encoding: ParameterEncoding = URLEncoding.default,

    headers: HTTPHeaders? = nil)


url은 요청할 URL이 되며

method는 요청 형식 (get, post, put, delete..등)

parameters는 요청 시 같이 보낼 파라미터들이 되며

encoding은 말그래도 encoding이며

header도 [String:String]형태로 보낼 수 있습니다.



위에서 일일이 추가 하던 것과는 다르게 확연히 다른 차이를 볼 수 있습니다.


훨씬 간결해서 보기도 편합니다.




request가 성공인지 실패인지를 필터를 하는 validate(statusCode: 200..<300)로 200~299사이의 statusCode결과만 받아올 수 있는 간편한 기능도 지원합니다.


저렇게 요청을 하면 


{

        "avatar_url" = "https://avatars3.githubusercontent.com/u/1?v=3";

        "events_url" = "https://api.github.com/users/mojombo/events{/privacy}";

        "followers_url" = "https://api.github.com/users/mojombo/followers";

        "following_url" = "https://api.github.com/users/mojombo/following{/other_user}";

        "gists_url" = "https://api.github.com/users/mojombo/gists{/gist_id}";

        "gravatar_id" = "";

        "html_url" = "https://github.com/mojombo";

        id = 1;

        login = mojombo;

        "organizations_url" = "https://api.github.com/users/mojombo/orgs";

        "received_events_url" = "https://api.github.com/users/mojombo/received_events";

        "repos_url" = "https://api.github.com/users/mojombo/repos";

        "site_admin" = 0;

        "starred_url" = "https://api.github.com/users/mojombo/starred{/owner}{/repo}";

        "subscriptions_url" = "https://api.github.com/users/mojombo/subscriptions";

        type = User;

        url = "https://api.github.com/users/mojombo";

    },

        {

        "avatar_url" = "https://avatars3.githubusercontent.com/u/2?v=3";

        "events_url" = "https://api.github.com/users/defunkt/events{/privacy}";

        "followers_url" = "https://api.github.com/users/defunkt/followers";

        "following_url" = "https://api.github.com/users/defunkt/following{/other_user}";

        "gists_url" = "https://api.github.com/users/defunkt/gists{/gist_id}";

        "gravatar_id" = "";

        "html_url" = "https://github.com/defunkt";

        id = 2;

        login = defunkt;

        "organizations_url" = "https://api.github.com/users/defunkt/orgs";

        "received_events_url" = "https://api.github.com/users/defunkt/received_events";

        "repos_url" = "https://api.github.com/users/defunkt/repos";

        "site_admin" = 1;

        "starred_url" = "https://api.github.com/users/defunkt/starred{/owner}{/repo}";

        "subscriptions_url" = "https://api.github.com/users/defunkt/subscriptions";

        type = User;

        url = "https://api.github.com/users/defunkt";

    }


이렇게 쉽게 요청을 할 수 있습니다.



Alamofire는 Request뿐만 아니라 Upload, Download등 여러가지를 지원하며


그에 맞는 기능을 최대한 편하게, 간결하게 사용할 수 있도록 제공합니다.