Skip to content

Commit

Permalink
Merge pull request #225 from mini-min/release/#184
Browse files Browse the repository at this point in the history
[FEAT] #184 - 리스트뷰, 메인 일부 서버 연결
  • Loading branch information
mini-min authored Dec 26, 2021
2 parents 730d8c6 + e173613 commit 4f37565
Show file tree
Hide file tree
Showing 11 changed files with 185 additions and 152 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@ extension UIViewController {
switch view {
case "QRScan":
toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 85,
y: self.view.frame.size.height - 230,
width: 170, height: 35))
y: self.view.frame.size.height - 230,
width: 170, height: 35))
case "copyID":
toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 100,
y: self.view.frame.size.height/2,
width: 200, height: 35))
y: self.view.frame.size.height/2,
width: 200, height: 35))
case "saveImage":
toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 85,
y: self.view.frame.size.height/2,
Expand All @@ -86,8 +86,8 @@ extension UIViewController {
width: 240, height: 35))
default:
toastLabel = UILabel(frame: CGRect(x: self.view.frame.size.width/2 - 85,
y: self.view.frame.size.height - 230,
width: 170, height: 35))
y: self.view.frame.size.height - 230,
width: 170, height: 35))
}

toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
Expand All @@ -103,4 +103,16 @@ extension UIViewController {
options: .curveEaseOut, animations: { toastLabel.alpha = 0.0 },
completion: {_ in toastLabel.removeFromSuperview() })
}

// MARK: UIWindow의 rootViewController를 변경하여 화면전환
func changeRootViewController(_ viewControllerToPresent: UIViewController) {
if let window = UIApplication.shared.windows.first {
window.rootViewController = viewControllerToPresent
UIView.transition(with: window, duration: 0.5, options: .transitionCrossDissolve, animations: nil)
} else {
viewControllerToPresent.modalPresentationStyle = .overFullScreen
self.present(viewControllerToPresent, animated: true, completion: nil)
}
}

}
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="19455" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="19529" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" useSafeAreas="YES" colorMatched="YES">
<device id="retina6_1" orientation="portrait" appearance="light"/>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="19454"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="19519"/>
<capability name="Named colors" minToolsVersion="9.0"/>
<capability name="Safe area layout guides" minToolsVersion="9.0"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,17 @@

import Foundation

// MARK: - CardList
// MARK: - CardListRequest
struct CardListRequest: Codable {
let cardID, title, createDate: String
let cardDates: [CardList]
}

// MARK: - CardList
struct CardList: Codable {
let cardID, title: String

enum CodingKeys: String, CodingKey {
case cardID = "cardId"
case title, createDate
case title
}
}
58 changes: 46 additions & 12 deletions NADA-iOS-forRelease/Sources/NetworkService/Card/CardAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,18 +47,32 @@ public class CardAPI {
}
}

func cardListFetch(userID: String, isList: Bool, offset: Int, completion: @escaping (NetworkResult<Any>) -> Void) {
func cardListFetch(userID: String, isList: Bool, offset: Int?, completion: @escaping (NetworkResult<Any>) -> Void) {
cardProvider.request(.cardListFetch(userID: userID, isList: isList, offset: offset)) { (result) in
switch result {
case .success(let response):
let statusCode = response.statusCode
let data = response.data

let networkResult = self.judgeCardListFetchStatus(by: statusCode, data)
completion(networkResult)

case .failure(let err):
print(err)
if isList == true {
switch result {
case .success(let response):
let statusCode = response.statusCode
let data = response.data

let networkResult = self.judgeCardListFetchStatus(by: statusCode, data)
completion(networkResult)

case .failure(let err):
print(err)
}
} else {
switch result {
case .success(let response):
let statusCode = response.statusCode
let data = response.data

let networkResult = self.judgeMainListFetchStatus(by: statusCode, data)
completion(networkResult)

case .failure(let err):
print(err)
}
}
}
}
Expand Down Expand Up @@ -115,7 +129,7 @@ public class CardAPI {
}
}

private func judgeCardListFetchStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {
private func judgeMainListFetchStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {

let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode(GenericResponse<CardListLookUpRequest>.self, from: data)
Expand All @@ -135,6 +149,26 @@ public class CardAPI {
}
}

private func judgeCardListFetchStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {

let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode(GenericResponse<CardListRequest>.self, from: data)
else {
return .pathErr
}

switch statusCode {
case 200:
return .success(decodedData.data ?? "None-Data")
case 400..<500:
return .requestErr(decodedData.msg)
case 500:
return .serverErr
default:
return .networkFail
}
}

private func judgeCardCreationStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {

let decoder = JSONDecoder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,11 @@ extension CardService: TargetType {

var headers: [String: String]? {
switch self {
case .cardDetailFetch, .cardListFetch, .cardDelete:
return Const.Header.bearerHeader
case .cardDetailFetch, .cardListFetch, .cardDelete, .cardListEdit:
return ["Content-Type": "application/json",
"Authorization": "Bearer " + UserDefaults.standard.string(forKey: Const.UserDefaults.accessToken)!]
case .cardCreation:
return Const.Header.basicHeader
case .cardListEdit:
return ["Content-Type": "application/json"]
}
}
}
22 changes: 21 additions & 1 deletion NADA-iOS-forRelease/Sources/NetworkService/User/UserAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public class UserAPI {
let statusCode = response.statusCode
let data = response.data

let networkResult = self.judgeStatus(by: statusCode, data)
let networkResult = self.judgeUserTokenReissueStatus(by: statusCode, data)
completion(networkResult)

case .failure(let err):
Expand Down Expand Up @@ -166,6 +166,26 @@ public class UserAPI {
}
}

private func judgeUserTokenReissueStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {

let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode(GenericResponse<UserWithTokenRequest>.self, from: data)
else {
return .pathErr
}

switch statusCode {
case 200:
return .success(decodedData.data ?? "None-Data")
case 400..<500:
return .requestErr(decodedData.msg)
case 500:
return .serverErr
default:
return .networkFail
}
}

private func judgeStatus(by statusCode: Int, _ data: Data) -> NetworkResult<Any> {
let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode(GenericResponse<String>.self, from: data)
Expand Down
3 changes: 3 additions & 0 deletions NADA-iOS-forRelease/Sources/SceneDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate {

if self.defaults.string(forKey: Const.UserDefaults.accessToken) != "" {
rootViewController = UIStoryboard(name: Const.Storyboard.Name.tabBar, bundle: nil).instantiateViewController(withIdentifier: Const.ViewController.Identifier.tabBarViewController)
} else {
rootViewController = UIStoryboard(name: Const.Storyboard.Name.login, bundle: nil)
.instantiateViewController(identifier: Const.ViewController.Identifier.loginViewController)
}
self.window?.rootViewController = rootViewController
self.window?.makeKeyAndVisible()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import KakaoSDKCommon
class CardListViewController: UIViewController {

// MARK: - Properties
var cardItems: [CardListDataModel] = []
var cardItems: [CardList] = []
var newCardItems: [Ordered] = []

// MARK: - IBOutlet Properties
@IBOutlet weak var cardListTableView: UITableView!
Expand All @@ -22,17 +23,14 @@ class CardListViewController: UIViewController {
super.viewDidLoad()

navigationBackSwipeMotion()

setCardList()
setLongPressGesture()

cardListTableView.register(CardListTableViewCell.nib(), forCellReuseIdentifier: "CardListTableViewCell")

cardListTableView.delegate = self
cardListTableView.dataSource = self

// FIXME: - 카드 리스트 조회 서버 테스트
// cardListFetchWithAPI(userID: "nada", isList: true, offset: 0)
cardListFetchWithAPI(userID: UserDefaults.standard.string(forKey: Const.UserDefaults.userID) ?? "", isList: true)
}

override func viewWillAppear(_ animated: Bool) {
Expand All @@ -47,17 +45,6 @@ class CardListViewController: UIViewController {
}

// MARK: - Functions
func setCardList() {
cardItems.append(contentsOf: [
CardListDataModel(title: "SOPT 28기 명함"),
CardListDataModel(title: "디자인 스터디 명함"),
CardListDataModel(title: "아이스브레이킹"),
CardListDataModel(title: "NADA 명함"),
CardListDataModel(title: "NADA 명함"),
CardListDataModel(title: "NADA 명함")
])
}

func setLongPressGesture() {
self.cardListTableView.allowsSelection = false

Expand Down Expand Up @@ -91,12 +78,16 @@ class CardListViewController: UIViewController {
let index = cardListTableView.indexPath(for: cell)

if index!.row > 0 {
cardListTableView.moveRow(at: index!, to: IndexPath(row: 0, section: 0))
self.cardItems.insert(self.cardItems.remove(at: index!.row), at: 0)
cardListTableView.reloadData()
cardListTableView.moveRow(at: index!, to: IndexPath(row: 0, section: 0))

// FIXME: - 카드 리스트 편집 서버 테스트
// self.putCardListEditWithAPI(request: CardListEditRequest(ordered: [Ordered(cardID: "cardA", priority: 1), Ordered(cardID: "cardB", priority: 0)]))
var count = 0
while cardItems.count > count {
newCardItems.append(Ordered(cardID: cardItems[count].cardID, priority: count))
count += 1
}
cardListEditWithAPI(request: CardListEditRequest(ordered: newCardItems))
}
}
}
Expand All @@ -109,20 +100,24 @@ extension CardListViewController: UITableViewDelegate {

// Swipe Action
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .normal, title: "삭제", handler: { (_ action, _ view, _ success) in
self.makeCancelDeleteAlert(title: "명함 삭제", message: "명함을 정말 삭제하시겠습니까?\n공유된 명함일 경우, 친구의 명함 모음에서도 해당 명함이 삭제됩니다.", cancelAction: { _ in
// 취소 눌렀을 때 액션이 들어갈 부분
}, deleteAction: { _ in
// FIXME: - 카드 삭제 서버 테스트
// self.deleteCardWithAPI(cardID: "cardA")
if indexPath.row == 0 {
return nil
} else {
let deleteAction = UIContextualAction(style: .normal, title: "삭제", handler: { (_ action, _ view, _ success) in
self.makeCancelDeleteAlert(title: "명함 삭제", message: "명함을 정말 삭제하시겠습니까?\n공유된 명함일 경우, 친구의 명함 모음에서도 해당 명함이 삭제됩니다.", cancelAction: { _ in
// 취소 눌렀을 때 액션이 들어갈 부분
}, deleteAction: { _ in
self.deleteCardWithAPI(cardID: self.cardItems[indexPath.row].cardID)
self.cardListTableView.reloadData()
})
})
})
deleteAction.backgroundColor = .red

let swipeActions = UISwipeActionsConfiguration(actions: [deleteAction])
swipeActions.performsFirstActionWithFullSwipe = false

return swipeActions
deleteAction.backgroundColor = .red
let swipeActions = UISwipeActionsConfiguration(actions: [deleteAction])
swipeActions.performsFirstActionWithFullSwipe = false
return swipeActions
}
}
}

Expand Down Expand Up @@ -154,12 +149,13 @@ extension CardListViewController: UITableViewDataSource {

// MARK: - Network
extension CardListViewController {
func cardListFetchWithAPI(userID: String, isList: Bool, offset: Int) {
CardAPI.shared.cardListFetch(userID: userID, isList: isList, offset: offset) { response in
func cardListFetchWithAPI(userID: String, isList: Bool) {
CardAPI.shared.cardListFetch(userID: userID, isList: isList, offset: nil) { response in
switch response {
case .success(let data):
if let card = data as? CardListRequest {
print(card)
self.cardItems = card.cardDates
self.cardListTableView.reloadData()
}
case .requestErr(let message):
print("getCardListFetchWithAPI - requestErr", message)
Expand Down Expand Up @@ -195,6 +191,8 @@ extension CardListViewController {
switch response {
case .success(let data):
print(data)
self.cardListFetchWithAPI(userID: UserDefaults.standard.string(forKey: Const.UserDefaults.userID) ?? "", isList: true)
self.cardListTableView.reloadData()
case .requestErr(let message):
print("deleteGroupWithAPI - requestErr", message)
case .pathErr:
Expand All @@ -211,7 +209,6 @@ extension CardListViewController {

// MARK: - Extension: 테이블 뷰 Drag & Drop 기능
extension CardListViewController {
// FIX: cyclomatic_complexity 워닝 발생 -> decision이 복잡해서라는데...일단 보류...
@objc func longPressCalled(gestureRecognizer: UIGestureRecognizer) {
guard let longPress = gestureRecognizer as? UILongPressGestureRecognizer else { return }
let state = longPress.state
Expand All @@ -221,6 +218,7 @@ extension CardListViewController {
// 최초 indexPath 변수
struct Initial {
static var initialIndexPath: IndexPath?
static var tabIndex: IndexPath?
}

// 스냅샷
Expand All @@ -237,6 +235,7 @@ extension CardListViewController {
case UIGestureRecognizer.State.began:
if indexPath!.row != 0 {
Initial.initialIndexPath = indexPath
Initial.tabIndex = indexPath
var cell: UITableViewCell? = UITableViewCell()
cell = cardListTableView.cellForRow(at: indexPath!)

Expand Down Expand Up @@ -301,12 +300,16 @@ extension CardListViewController {

}, completion: { (finished) -> Void in
if finished {
var count = 0
while self.cardItems.count > count {
self.newCardItems.append(Ordered(cardID: self.cardItems[count].cardID, priority: count))
count += 1
}
self.cardListEditWithAPI(request: CardListEditRequest(ordered: self.newCardItems))

Initial.initialIndexPath = nil
MyCell.cellSnapshot!.removeFromSuperview()
MyCell.cellSnapshot = nil

// FIXME: - 카드 리스트 편집 서버 테스트
// self.putCardListEditWithAPI(request: CardListEditRequest(ordered: [Ordered(cardID: "cardA", priority: 1), Ordered(cardID: "cardB", priority: 0)]))
}
})
}
Expand Down
Loading

0 comments on commit 4f37565

Please sign in to comment.