Skip to content

Commit

Permalink
improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
kvyatkovskys committed Feb 28, 2023
1 parent e1eac4c commit 0a33b9a
Show file tree
Hide file tree
Showing 5 changed files with 55 additions and 42 deletions.
2 changes: 1 addition & 1 deletion DemoLogger/DemoLogger/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ POST https://practiceapp-dev.symplast.com/AppActions/Stats (200)BODY: {
[Result]: success(5941 bytes)
"""
await withTaskGroup(of: Void.self) { group in
for _ in 0 ..< 1 {
for _ in 0..<50 {
group.addTask {
await KVKLogger.shared.network(text, type: .debug)
}
Expand Down
4 changes: 4 additions & 0 deletions DemoLogger/DemoLogger/DemoLoggerApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
//

import SwiftUI
import KVKLogger

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {

Expand All @@ -28,6 +29,9 @@ struct DemoLoggerApp: App {
var body: some Scene {
WindowGroup {
ContentView()
.task {
KVKLogger.shared.configure()
}
}
}

Expand Down
31 changes: 22 additions & 9 deletions Sources/KVKLogger/KVKLogger.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import CoreData

open class KVKLogger {

private let store = KVKPersistenceСontroller.shared
let store: KVKPersistenceСontroller

public static let shared = KVKLogger()
/// Debug Mode
Expand All @@ -21,7 +21,20 @@ open class KVKLogger {

@ObservedObject var vm = KVKLoggerVM()

public init() {}
public init() {
store = KVKPersistenceСontroller()
}

public func configure() {
let urls = store.container.persistentStoreDescriptions
.compactMap({ $0.url?.lastPathComponent })
.joined(separator: ", ")
if urls.isEmpty {
debugPrint("Problem with configuring local DB!")
return
}
debugPrint("Local DB: [\(urls)] is configured!")
}

public func log(_ items: Any...,
status: KVKStatus = .info,
Expand Down Expand Up @@ -64,13 +77,13 @@ open class KVKLogger {
let date = Date()
if isEnableSaveIntoDB {
let item = store.getNewItem()
item?.createdAt = date
item?.status_ = status?.rawValue
item?.logType = logType
item?.type = type
item?.details = details
item?.items = items
item?.data = data
item.createdAt = date
item.status_ = status?.rawValue
item.logType = logType
item.type = type
item.details = details
item.items = items
item.data = data
store.save()
}

Expand Down
6 changes: 3 additions & 3 deletions Sources/KVKLogger/KVKLoggerProxyView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import SwiftUI

public struct KVKLoggerView: View {
private let persistenceContainer = KVKPersistenceСontroller.shared
private let persistenceContainer = KVKLogger.shared.store
@Environment (\.scenePhase) private var scenePhase

public init() {}
Expand Down Expand Up @@ -168,13 +168,13 @@ struct KVKLoggerProxyView: View {
case .clearAll:
if #available(iOS 15.0, macOS 12.0, *) {
Button(role: .destructive) {
KVKPersistenceСontroller.shared.deleteAll()
viewContext.deleteAll()
} label: {
Text(item.item.title)
}
} else {
Button {
KVKPersistenceСontroller.shared.deleteAll()
viewContext.deleteAll()
} label: {
Text(item.item.title)
}
Expand Down
54 changes: 25 additions & 29 deletions Sources/KVKLogger/KVKPersistenceСontroller.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,14 @@

import CoreData

struct KVKPersistenceСontroller {

static let shared = KVKPersistenceСontroller()

final class KVKPersistenceСontroller {

let container: NSPersistentContainer
let backgroundContext: NSManagedObjectContext
var viewContext: NSManagedObjectContext {
container.viewContext
}

init(inMemory: Bool = false) {
let dbName = dataBaseURL.lastPathComponent
if inMemory {
Expand All @@ -34,41 +32,21 @@ struct KVKPersistenceСontroller {
container.persistentStoreDescriptions = [store]
container.loadPersistentStores { (desc, error) in
if let error = error as? NSError {
print("Unresolved error \(error), \(error.userInfo)")
debugPrint("Unresolved error \(error), \(error.userInfo)")
}
}
backgroundContext = container.newBackgroundContext()
container.viewContext.automaticallyMergesChangesFromParent = true
container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump
backgroundContext = container.newBackgroundContext()
}

func getNewItem() -> ItemLog? {
guard container.persistentStoreDescriptions.first?.url != nil else { return nil }
return ItemLog(context: backgroundContext)
func getNewItem() -> ItemLog {
ItemLog(context: backgroundContext)
}

func save() {
guard container.persistentStoreDescriptions.first?.url != nil else { return }
backgroundContext.saveContext()
}

func deleteAll() {
do {
let fetchRequest: NSFetchRequest<NSFetchRequestResult>
fetchRequest = NSFetchRequest(entityName: ItemLog.entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
deleteRequest.resultType = .resultTypeObjectIDs
let batchDelete = try viewContext.execute(deleteRequest) as? NSBatchDeleteResult

guard let deleteResult = batchDelete?.result as? [NSManagedObjectID] else { return }

let deletedObjects: [String: Any] = [NSDeletedObjectsKey: deleteResult]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: deletedObjects, into: [viewContext])
} catch {
let nsError = error as NSError
print("Unresolved error \(nsError), \(nsError.userInfo)")
}
}

private let dataBaseURL: URL = {
let url = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first
Expand Down Expand Up @@ -140,6 +118,24 @@ extension NSAttributeDescription {

extension NSManagedObjectContext {

func deleteAll() {
do {
let fetchRequest: NSFetchRequest<NSFetchRequestResult>
fetchRequest = NSFetchRequest(entityName: ItemLog.entityName)
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
deleteRequest.resultType = .resultTypeObjectIDs
let batchDelete = try execute(deleteRequest) as? NSBatchDeleteResult

guard let deleteResult = batchDelete?.result as? [NSManagedObjectID] else { return }

let deletedObjects: [String: Any] = [NSDeletedObjectsKey: deleteResult]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: deletedObjects, into: [self])
} catch {
let nsError = error as NSError
debugPrint("Unresolved error \(nsError), \(nsError.userInfo)")
}
}

func saveContext() {
guard hasChanges else { return }

Expand Down

0 comments on commit 0a33b9a

Please sign in to comment.