UserDefaults로부터 값을 반영하고 해당 사용자 디폴트의 값이 변경될 때 뷰를 무효화(invalidate)하는 프로퍼티 래퍼 타입이다.

 

AppStorage는 작은 데이터 또는 짧은 String 같은 내용을 저장하는 부분으로 값이 변경되면 뷰에 바로 적용시킨다.

AppStorage 프로퍼티 래퍼는 date 구조체를 싫어한다고 한다.

 

다음 예제 코드는 처음 실행했을 때 시간값을 저장하였다가 앱 종료 후 다시 들어갔을 때 얼마만에 앱을 재실행하는지 화면에 보여주는 코드

import SwiftUI

struct ContentView: View {
   @AppStorage("interval") var interval = Date.timeIntervalSinceReferenceDate
   @State private var message: String = ""

   var body: some View {
      HStack {
         Text("\(message)")
            .lineLimit(nil)
      }.onAppear {
         let calendar = Calendar.current
         let lastDate = Date(timeIntervalSinceReferenceDate: interval)
         let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: lastDate, to: Date())
         message = "You haven't use this app in \(components.year!) years, \(components.month!) months, \(components.day!) days, \(components.hour!) hours, \(components.minute!) minutes, \(components.second!) seconds"
         interval = Date.timeIntervalSinceReferenceDate
      }
   }
}
#Preview {
   ContentView()
}

 

'SwiftUI' 카테고리의 다른 글

URL  (0) 2023.11.08
Files  (0) 2023.11.08
CryptoKit in SwiftUI - 비밀번호 암호화  (0) 2023.11.07
Errors - Throwing Errors, Handling Errors, Results  (0) 2023.11.07
Image Renderer  (0) 2023.11.07
ytw_developer