ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Swift With REST API (using Alamofire, in progress )
    미완성 2022. 3. 18. 01:07

    TODO Server: https://github.com/hanmok/TodoServer.git
    TODO SwiftCode : https://github.com/hanmok/TodoHabitREST

    let baseUrl = "http://localhost:5001"
    let targetUrl = "http://localhost:5001/todos"

     

     

     

     

    먼저, Alamofire 의 도움을 받지 않고 REST API 호출하는 법

    1. GET

    func getOneTodo(id: String, completion: @escaping (Result<Todo2, Error>) -> Void ) {
            let url = "\(baseUrl)/\(id)"
            guard let URL = URL(string: url) else { return }
    
            var urlReq = URLRequest(url: URL)
            
            urlReq.httpMethod = HttpMethodType.get
            
            let task = URLSession.shared.dataTask(with: urlReq) { data, response, error in
                
                if let err = error {
                    print("error: \(err)")
                    return
                    
                }
                guard let data = data else { return }
                
                DispatchQueue.main.async {
                    do {
                        let todo = try JSONDecoder().decode(Todo2.self, from: data)
                        completion(.success(todo))
                    } catch {
                        print("error: \(error.localizedDescription)")
                        completion(.failure(error))
                    }
                }
            }.resume()
        }

     

    func getAllTodos(completion: @escaping (Result<[Todo2], Error>) -> Void ) {
            let url = "\(targetUrl)"
            guard let URL = URL(string: url) else { return }
            var urlReq = URLRequest(url: URL)
            
            urlReq.httpMethod = HttpMethodType.get
            
            let task = URLSession.shared.dataTask(with: urlReq) { data, response, error in
                if let e = error {
                    print("error: \(e)")
                    return
                }
                
                guard let data = data else { return }
                
                DispatchQueue.main.async {
                    do {
                        // json object sent from the server.
                        let todos = try JSONDecoder().decode([Todo2].self, from: data)
                        print("todos: \(todos)")
                        completion(.success(todos))
                    } catch {
                        print("error: \(error.localizedDescription)")
                        completion(.failure(error))
                    }
                }
            }.resume()
        }

     

    POST, PATCH 의 경우 Alamofire 을 이용할 때는 동작하지만, 쓰지 않고서는 왜 제대로 작동하는지 잘 모르겠음..

    Alamofire documentation 을 보고 역으로 파악하기 위해 찾아보는중. 

     

     

    4. DELETE

    func deleteOneTodo(id: String, completion: @escaping (Error?) -> Void) {
            let url = "\(targetUrl)/\(id)"
            guard let URL = URL(string: url) else { return }
            var urlReq = URLRequest(url: URL)
    
            urlReq.httpMethod = HttpMethodType.delete
    
            let task = URLSession.shared.dataTask(with: urlReq) { data, response, error in
    
                guard error == nil else {
                    print("error : \(error?.localizedDescription)")
                    completion(error)
                    return
                }
    
                completion(nil)
    
            }.resume()
        }
    func deleteAllTodos() {
            
            let url = "\(targetUrl)"
            guard let URL = URL(string: url) else { return }
            var urlReq = URLRequest(url: URL)
            urlReq.httpMethod = HttpMethodType.delete
            
            let task = URLSession.shared.dataTask(with: urlReq) { data, response, error in
                guard error == nil else { print("error!! : \(error)"); return }
                
                print("response: \(response)")
            }.resume()
        }

     

     

     

     

    Alamofire

    1. GET

    func getAll() {
        AF.request("http://localhost:5001/todos").response { response in
            let newData = String(data: response.data!, encoding: .utf8)
            
            do {
                self.todos = try JSONDecoder().decode([Todo2].self, from: newData!.data(using: .utf8)!)
            } catch {
                print("failed to decode!")
            }
            print("todo: \(self.todos)")
            print("todoCount :\(self.todos.count)")
        }
    }
    func getOne() {
        AF.request("http://localhost:5001/todos/614b423a799255beccc10a40").response { response in
            let newData = String(data: response.data!, encoding: .utf8)
            
            do {
                let newTodo = try JSONDecoder().decode(Todo2.self, from: newData!.data(using: .utf8)!)
    			// do something with new Todo 
            } catch {
                print("failed to decode!")
            }
    
        }
    }

    2. POST

    func postTodoAF(onDate: String, title: String) {
        AF.request("\(baseUrl)/todos", method: .post, parameters: ["title": title, "onDate": onDate ], encoding: URLEncoding.httpBody, headers: HTTPHeaders.init()).responseJSON { response in
            print("addtodo, \(response)")
        }
    }

    3. PATCH

    func patchOne(id: String, newTitle: String, newOnDate: String) {
        AF.request("\(baseUrl)/todos/\(id)", method: .patch, parameters: ["title": newTitle, "onDate": newOnDate ], encoding: URLEncoding.httpBody, headers: HTTPHeaders.init()).responseJSON { response in
            print("patchOne, \(response)")
        }
    }

    4. DELETE

    func deleteTodosAF() {
        AF.request(targetUrl, method: .delete,   headers: HTTPHeaders.init()).responseData { response in
            print("response: \(response)")
        }
    }
    func deleteTodoAF(id: String) {
        AF.request(targetUrl + "/" + id, method: .delete,   headers: HTTPHeaders.init()).responseData { response in
            print("response: \(response)")
        }
    }



    코드를 일관성 있게 바꾸기.
    BaseUrl or targetUrl 을 쓰든가 주소를 직접 쓰든가.
    Parsing 할 때 과정을 더 공부하기.
    AF 를 통해 가져온 것을 Swift 의 Object 로 바꾸는 과정

    위 과정은 https://stackoverflow.com/questions/30838752/how-to-convert-json-data-from-alamofire-to-swift-objects

     

    How to convert json data from alamofire to swift objects

    hi there im making a photo viewer app in swift using swift 1.1 in xcode 6.2 i am a having trouble trying to convert json response from alamofire to swift objects.i have used swiftyjson lib...

    stackoverflow.com


    여기 참고해서 만들어보기.
    (그런데 TiStory 버그가 좀 있다... )

    '미완성' 카테고리의 다른 글

    Deep Memo ( 미완성 )  (0) 2021.11.21
    Human Interface Guidelines - Bars - Sidebars (미완성)  (0) 2021.11.21
Designed by Tistory.