포스트

7주차 과제 (6)

중복처리

곰곰히 생각을 해보다가 똑같은 페이지를 로드했을때 담게되면 중복값이 그대로 DB에 들어갈것같아

중복이라는 예외처리를 해보려 한다.

Simulator Screenshot - iPhone 15 Pro - 2024-04-11 at 04 23 40

현재는 이렇게 중복된 값이 들어가게 된다.

1~100 까지는 너무나 광범위하니 1~5로 조정하여 테스트를 진행한다.

1
2
3
4
5
6
7
 do {         
            savedList = try context.fetch(request)
            
        } catch {
            let alert = alertManager.makingAlert(title: "에러 발생", body: "데이터를 로드 하던 중 오류가 발생했습니다.")
            self.present(alert, animated: true)
        }

우선 데이터를 로드한다.

if savedList.filter({$0.id == list[0].id}).count == 1

if문에 다음과 같이 적었다.

DB의 값을 savedList에 저장을 하고, fetchRequest에서 가져온 값의 id와 비교를 하는 것이다.

이때 count가 1이 된다는것은, 저장되어있는 값과 현재 불러온 값이 일치하는게 하나 존재한다는 뜻이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
@IBAction func saveListBtn(_ sender: UIButton) {

        // new
        do {
            
            savedList = try context.fetch(request)
            
        } catch {
            let alert = alertManager.makingAlert(title: "에러 발생", body: "데이터를 로드 하던 중 오류가 발생했습니다.")
            self.present(alert, animated: true)
        }
        
        if savedList.filter({$0.id == list[0].id}).count == 1 { // new
            
            let alert = alertManager.makingAlert(title: "중복된 값이 존재합니다", body: "이미 해당 정보가 위시리스트에 저장되어있습니다.")
            self.present(alert, animated: true)
            
        } else {
            
            let newItem = Lists(context: self.context)
            newItem.id = Int64(list[0].id)
            newItem.title = list[0].title
            newItem.price = Int64(list[0].price)
            newItem.discountPercentage = list[0].discountPercentage
            
            do
            {
                try context.save()
                
            } catch {
                let alert = alertManager.makingAlert(title: "에러발생", body: "\(error.localizedDescription)가 발생했습니다.")
                self.present(alert, animated: true)
                
            }
            
        }
        
        savedList.removeAll()
        dataManager.fetchRequest()
    
    }

이렇게 좀 더 디테일하게 구분을 해주었다.

simulator_screenshot_0F517CB8-D5F8-421F-B390-F68F997A88A6

이렇게 미리 1~5 페이지 값을 다 담아 두었다.

simulator_screenshot_BE70DAB8-4AE8-481E-9A54-ABCFAF7F66F0

이렇게 alert가 뜨고, db에도 더이상 값이 들어가지 않는다.

AlertManager 생성

기존에 계속 무의미하게 let alert = UIAlertController~ 이렇게 무의미하게 계속 생성하는것 같아서

함수로 구현해주었다.

1
2
3
4
5
6
7
8
9
class AlertManager {
    
    func makingAlert (title: String, body: String) -> UIAlertController {
        let alert = UIAlertController(title: title, message: body, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "확인", style: .default))
        
        return alert
    }
}

title과 본문내용인 body를 parameter로 받게 하였다.

위에 예외처리를 하면서 테스트를 해본결과 작동이 잘 되는것을 확인했다.

id순으로 정렬하여 보여주기.

현재는 등록된 순으로 tableview에 보여지게 된다.

이걸 id순으로 정렬하여 보여지게 하자.

simulator_screenshot_67DC1D9A-E1D8-4C4E-A411-716FA4C4C248

현재는 뒤죽박죽이다.

tableVC.savedList = savedList.sorted(by: {$0.id < $1.id})

클로저를 사용하여 정렬한다.

Simulator Screenshot - iPhone 15 Pro - 2024-04-11 at 05 33 20

완료.

삭제할때 꼬이지않고 DB에서 잘 지워지는것도 확인했다.

기능 업그레이드.

생각해보니 현재 ImageView를 사용했는데, 지난번 프로젝트때처럼 여러 이미지들에 대해 가로로 스크롤 해셔 보여주는것도 좋을 것 같아서 해당부분을 더 발전시켜보려한다.

참고사이트

이전에 팀원분을 도와주면서 해당 기능에 대한 매커니즘은 파악한 상태여서 내 코드에 맞게 조정을 하면 될듯하다.

그리고 할인 전, 후 가격을 같이 보여주면 좋을 것 같다고해서 그 부분도 더 보강 해보려한다.

지난 프로젝트의 아이디어가 생각나서 imageview에서 scrollview로 바꾸었다.

1
2
3
4
5
6
7
8
9
10
11
12
func addImage() {
        
        for i in 0 ..< list[0].images.count - 1 {
            let imageView = UIImageView()
            let xPos = imageScrollView.frame.width * CGFloat(i)
            imageView.frame = CGRect(x: xPos, y: 0, width: imageScrollView.bounds.width, height: imageScrollView.bounds.height)
            imageView.load(url: URL(string: list[0].images[i])!)
            imageScrollView.addSubview(imageView)
            imageScrollView.contentSize.width = imageView.frame.width * CGFloat(i + 1)
        }
        
    }

안에서 이미지뷰가 새로 갱신이 되는 스타일이다.

이전에는 viewDidload에 해당 함수를 넣었겠지만 이번엔 다르다.

api통신 이후 값이 들어오므로

1
2
3
4
5
6
7
8
9
10
 DispatchQueue.main.async {

                let price = self.numberFormatter.string(from: Double(self.list[0].price) * (100.00 - self.list[0].discountPercentage) / 100 as NSNumber)
                self.titleLabel.text = self.list[0].title
                self.bodyLabel.text = self.list[0].description
                self.priceLabel.text = "\(self.numberFormatter.string(from: self.list[0].price as NSNumber) ?? "0") $"
                self.discountedLabel.text = "할인 적용: \(price ?? "0")$"
                self.addImage() // new

            }

여기에 넣어준다.

Apr-11-2024 12-05-07

우선 잘되는걸 확인했다.

하지만 내가 직접 스크롤을 하지 않는 이상 보이지 않기에 PageControl도 추가해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
extension ViewController: UIScrollViewDelegate {
    
    func setPageCount () { // page의 카운트를 정해줌.
        imagePageControl.numberOfPages = list[0].images.count - 1
    }
    
    private func setPageControlSelectedPage(currentPage:Int) { // 현재 페이지를 보여줌
        imagePageControl.currentPage = currentPage
      }
    
    func scrollViewDidScroll(_ imageScrollView: UIScrollView) {
        let value = imageScrollView.contentOffset.x/imageScrollView.frame.size.width
        setPageControlSelectedPage(currentPage: Int(round(value)))
    }
    
}

참고사이트와 코드전개는 동일.

이때 주의해야할 점이라면 현재 scrollView가 2개이기에 delegate를 사용할때 매칭을 잘 해줘야한다.

scrollView / imageScrollView 두개가 있는데

scrollView로 하게되면 pull to refresh할때 scrollViewDidScroll 메서드가 트리거된다.

Apr-11-2024 14-22-44

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.