일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 클로저의 캡슐화
- 한국어 개인정보처리방침
- WeatherManager
- weatherKit
- CoreLocation
- Required Reason API
- App Store Connect
- 단일 책임원칙
- UIAlertAction
- Xcode
- 러닝기록앱
- AnyObject
- addannotation
- xcode로 날씨앱 만들기
- 영문 개인정보처리방침
- font book
- CLLocationManagerDelegate
- 서체관리자
- weak var
- UICollectionViewFlowLayout
- swift
- MKMapItem
- MKMapViewDelegate
- 러닝타이머
- Timer
- Startign Assignments
- RunningTimer
- dispatchsource
- Protocol
- SwiftUI Boolean 값
Archives
- Today
- Total
VesselWheel
러닝기록 타이머를 정지하며 코어데이터에 저장하기(작성중) 본문
코어데이터를 활용하기 위한 CoreDataManager
더보기
//
// CoreDataManager.swift
// Run-It
//
// Created by t2023-m0024 on 2/29/24.
//
import Foundation
import CoreData
import KakaoSDKUser
class CoreDataManager {
static let shared = CoreDataManager()
private init() {}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Run_It")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
print("Unresolved error \(error), \(error.userInfo)")
// Handle the error appropriately
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
// MARK: - User Operations
func createUser(email: String, name: String, profilePhoto: Data) -> User? {
let context = persistentContainer.viewContext
// Correct way to create a new User entity
guard let entity = NSEntityDescription.entity(forEntityName: "User", in: context) else {
print("Failed to create entity description for User")
return nil
}
let user = User(entity: entity, insertInto: context)
user.userId = UUID()
user.email = email
user.name = name
user.createdAt = Date()
// Assume profilePhoto is stored as Data
user.profilePhoto = profilePhoto
do {
try context.save()
return user
} catch {
print("Failed to create user: \(error)")
return nil
}
}
// Add similar functions for other CRUD operations on User and other entities
// For example: fetchUsers(), updateUser(), deleteUser(), etc.
// MARK: - Destination Operations
// Add functions for creating, reading, updating, and deleting destinations
// MARK: - Favorite Operations
// Add functions for managing favorites
// MARK: - PlaceInfo Operations
// Add functions for managing place information
// MARK: - RunningRecord Operations
func createRunningRecord(time: Int, distance: Double, pace: Double) -> RunningRecord? {
let context = persistentContainer.viewContext
guard let entity = NSEntityDescription.entity(forEntityName: "RunningRecord", in: context) else {
print("Failed to create entity description for RunningRecord")
return nil
}
let record = RunningRecord(entity: entity, insertInto: context)
// record.recordId = UUID()
record.id = UUID()
record.time = Int32(time)
record.distance = distance
record.pace = pace
// record.createdAt = Date()
print("CoreData id: \(String(describing: record.id)) Time: \(record.time), Distance: \(record.distance), Pace: \(record.pace)")
do {
try context.save()
return record
} catch {
print("Failed to create running record: \(error)")
return nil
}
}
// MARK: - RunningRecord Operations
func fetchRunningRecords() -> [RunningRecord] {
let context = persistentContainer.viewContext
let fetchRequest: NSFetchRequest<RunningRecord> = RunningRecord.fetchRequest()
do {
let records = try context.fetch(fetchRequest)
return records
} catch {
print("Failed to fetch running records: \(error)")
return []
}
}
}
@objc private func stopRunning() {
print("TappedButton - stopRunning()")
print("stop Time: \(self.time), Distance: \(self.distance), Pace: \(self.pace)")
let alert = UIAlertController(title: "운동을 완료하시겠습니까?", message: "근처 편의점에서 물 한잔 어떻신가요?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "운동 완료하기", style: .default, handler: { _ in
self.runningTimer.stop()
CoreDataManager.shared.createRunningRecord(time: self.time, distance: self.distance, pace: self.pace)
// let records = CoreDataManager.shared.fetchRunningRecords()
// for record in records {
// print("CoreData Time: \(record.time), Distance: \(record.distance), Pace: \(record.pace)")
// }
let mainTabBarViewController = MainTabBarViewController()
mainTabBarViewController.modalPresentationStyle = .fullScreen
self.present(mainTabBarViewController, animated: true)
}))
alert.addAction(UIAlertAction(title: "취소하기", style: .destructive, handler: nil))
self.present(alert, animated: true, completion: nil)
}
'Xcode Study' 카테고리의 다른 글
MapKit으로 출발지, 도착지 그리고 경로 구현하기(.feat CLLocationManagerDelegate, MKMapViewDelegate) (0) | 2024.03.05 |
---|---|
Mapkit의 지도에 MKLocalSearch활용하여 검색된 annotation 노출하기 (0) | 2024.03.04 |
SceneDeleagte(for 러닝기록 타이머) (0) | 2024.02.29 |
러닝기록 타이머 만들기(3/3)(with dispatchsource ) (0) | 2024.02.27 |
Background Tasks (0) | 2024.02.27 |