728x90
글쓰기 API를 이용해, 트윗 글쓰기를 해보려고 합니다.
1. API 명세서 확인하기
2. API 명세서에 맞게 Router생성
[Router/TwitPostRouter.swift]
- Router 객체에서 경로와 HTTP 메소드 설정을 해준다.
- 파라미터에 content 와 writer를 넣어준다.
import Foundation
import UIKit
import Alamofire
enum TwitPostRouter {
case postTwit(content: String, writer: Writer)
}
extension TwitPostRouter: BaseRouter {
var path: String {
return "/twit"
}
var method: HTTPMethod {
return .post
}
var header: HeaderType {
return .auth
}
var parameters: RequestParams {
switch self {
case .postTwit(let content, let writer):
let body: [String:Any] = [
"content": content,
"writer" : [
"_id" : writer.id,
"userName" : writer.userName
]
]
return .requestBody(body)
}
}
}
[Model/Writer.swift]
import Foundation
struct Writer: Codable {
let id: String
let userName: String
enum CodingKeys: String, CodingKey {
case id = "_id"
case userName
}
}
3. Service 파일 생성
- request 안에 TwitPostRouter.postTwit 메소드를 호출하고, 매개변수(post, writer)를 넣어줍니다.
- 성공한다면, data를 Writer객체로 decode 해준다.
import Foundation
import UIKit
import Alamofire
class TwitPostService: BaseService {
static let shared = TwitPostService()
private override init() { }
func postTwit(content: String, writer: Writer, completion: @escaping (NetworkResult<Any>) -> (Void)) {
AFmanager.request(TwitPostRouter.postTwit(content: content, writer: writer))
.validate(statusCode: 200...500)
.responseData { response in
switch response.result {
case .success:
guard let statusCode = response.response?.statusCode else { return }
guard let data = response.data else { return }
let networkResult = self.judgeStatus(by: statusCode, data, Writer.self)
completion(networkResult)
case .failure(let err):
print(err.localizedDescription)
}
}
}
}
4. ViewController 생성하기
- 글쓰기 작성 버튼을 클릭하면, postTwit() 메소드에 요청을 보냅니다.
private func twitButtonDidTap(_ button: UIButton) {
postTwit()
self.dismiss(animated: true)
}
private func postTwit() {
guard let content = twitTextView.text
else { return }
let userId = "id내용받아오기"
let userName = "Username"
TwitPostService.shared.postTwit(content: content, writer: Writer(id: userId, userName: userName)) { result in
switch result {
case .success:
print("성공")
case .requestErr:
print("requestErr")
case .pathErr:
print("pathErr")
case .serverErr:
print("serverErr")
case .networkFail:
print("networkFail")
}
}
}
728x90