inverse a core data boolean value - swift

In my swift code below the goal would be to inverse whatever the boolean sign is. Right now the code just deletes the current boolean value which is at user1. So say user1 is true when it is inserted in into the function I would like to reverse to false instead of deleting it in core data how do I do that?
class ViewController: UIViewController {
override func viewDidLo
if CoredataHandler.deleteObject(user: user![1]) {
user = CoredataHandler.fetchObject()
print("after single")
for i in user! {
print(i.username!)
}
}
}
}
class CoredataHandler : NSManagedObject {
private class func getContext() -> NSManagedObjectContext {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.persistentContainer.viewContext
}
class func fetchObject() -> [User]?
{
let context = getContext()
var user : [User]? = nil
do {
user = try context.fetch(User.fetchRequest())
return user
} catch {
return user
}
}
class func deleteObject(user: User) -> Bool
{
let context = getContext()
let delete = NSBatchDeleteRequest(fetchRequest: User.fetchRequest())
do {
try context.execute(delete)
return true
} catch {
return false
}
}
}

Related

counting the amount of attributes saved from core data helper class

In my swift code below the goal is to get the amount of core data attributes saved into core data. I am receiving the error message No exact matches in call to initializer at indexBox.text = String(info?). I don't know what to do next.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let info = CoredataHandler.fetchObject()?.count
indexBox.text = String(info?)
}
}
class CoredataHandler : NSManagedObject {
class func fetchObject() -> [User]?
{
let context = getContext()
var user : [User]? = nil
do {
user = try context.fetch(User.fetchRequest())
return user
} catch {
return user
}
}
}

delete boolean value at specific point in set

In my swift code below the goal is to delete the first item in the core data boolean attribute. My code is not working below but its close to what I used to successfully fetch a boolean value. I don't really know what to add. There is a base class and a helper class.
class ViewController: UIViewController {
func deleteBool(imageNo:Int) {
// first check the array bounds
let info = helpBool.shareInstance.fetchBool()
if info.count > imageNo {
}
}
override func viewDidLoad() {
super.viewDidLoad()
deleteBool(imageNo: 1)}}
HELPER CLASS
class helpBool: UIViewController{
static let shareInstance = helpBool()
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func deleteBool(_ boolean: Bool) {
let imageInstance = OnOff(context: context)
imageInstance.bool = boolean
do {
try context.delete()
print("text is saved")
} catch {
print(error.localizedDescription)
}
}

UnitTest does't work properly for MVP pattern Swift

I'm trying to write some UnitTests for the first time. My pattern is MVP and I'm trying to test my Presenter. I've created mock class: class TeamViewMock: TeamViewPresenterProtocol { }. It contains all the methods from my real Presenter. Inside the each method I'm trying to set the new value for the property, so when the method called - property should get a new value.
Only one property gets new value out of 4 and I've no clue why the other ones didn't get it.
You may see it in the following code
import XCTest
#testable import NHL
class TeamViewPresenterTest: XCTestCase {
var presenter: TeamViewPresenter!
var viewMock: TeamViewMock!
func setupPresenter() {
viewMock = TeamViewMock()
presenter = TeamViewPresenter(with: viewMock)
}
func testGetData() {
setupPresenter()
presenter.getData(completion: {_ in })
XCTAssertTrue(viewMock.isStart) // This one works and returns true
XCTAssertTrue(viewMock.isStop) // Return error
XCTAssertTrue(viewMock.isEndRefreshing) // Return error
XCTAssertTrue(viewMock.isReload) // Return error
}
}
class TeamViewMock: TeamViewPresenterProtocol {
var isStart = false
var isStop = false
var isEndRefreshing = false
var isReload = false
func startAnimating() {
self.isStart = true // Testing stops here and doesn't go any further...
}
func stopAnimating() {
self.isStop = true
}
func endRefreshing() {
self.isEndRefreshing = true
}
func reloadView(_ teams: NHLDTO) {
self.isReload = true
}
}
class TeamViewPresenter {
// MARK: - Public Properties
private weak var view: TeamViewPresenterProtocol?
public let dataFetcherService = DataFetcherService()
// MARK: - Initializers
init(with view: TeamViewPresenterProtocol) {
self.view = view
}
// MARK: - Public Methods
public func getData(completion: #escaping (AppError) -> Void) {
view?.startAnimating() // Testing stops here and doesn't go any further, but still returns true for the property isStart and error for the rest
dataFetcherService.fetchTeamData { [weak self] result in
guard let self = self else { return }
switch result {
case .failure(let error):
completion(error)
print(error)
case .success(let teams):
guard let teams = teams else { return }
self.view?.reloadView(teams)
self.view?.stopAnimating()
self.view?.endRefreshing()
}
}
}
}
protocol TeamViewPresenterProtocol: AnyObject {
func startAnimating()
func stopAnimating()
func reloadView(_ teams: NHLDTO)
func endRefreshing()
}

Swift - Enum in UIView shows up as nil when set from other ViewController

I'm having trouble with this Firebase application. I have an enum inside a UIView that shows up as nil even when I set it in viewDidLoad(). The UIView is just a header view, with the enum serving through a switch statement to determine which button to display for which user type. Here's the code for the UIView (shortened to just show necessary code for readability):
enum HeaderViewOptions: Int {
case partner
case client
}
class HeaderView: UIView {
var options: HeaderViewOptions!
//...
override init(frame: CGRect) {
super.init(frame: frame)
//...
switch options {
case .partner:
addSubview(addServiceButton)
//...
case .client:
addSubview(searchButton)
//...
case .none:
break
}
}
}
Here's where the series of functions and variables in order inside the ViewController that set the options variable:
override func viewDidLoad() {
super.viewDidLoad()
checkUser()
}
func checkUser() {
if Auth.auth().currentUser?.uid == nil {
//...
} else {
configure()
}
}
func configure() {
//...
fetchUserData()
//...
}
func fetchUserData() {
guard let currentUid = Auth.auth().currentUser?.uid else { return }
Services.shared.fetchUserData(uid: currentUid) { user in
self.user = user
}
}
private var user: User? {
didSet {
if user?.accountType == .partner {
headerView.options = .partner
} else {
headerView.options = .client
}
}
}
The accountType property for the User object has the same enum options as the HeaderView class.
Update your async function
func fetchUserData() {
guard let currentUid = Auth.auth().currentUser?.uid else { return }
Services.shared.fetchUserData(uid: currentUid) {[weak self] user in
self?.user = user
DispatchQueue.main.async {
self?.configureButtonsInView() // add buttons here
}
}
}

How to access variable in Document.swift from another class?

In CoreData document I have an entity SpaceLocation which is set of different SpaceLocations. One of them is default / current one, necessary for editing document.
It's defined in main Document.swift as:
#objc var defaultSpaceLocation: SpaceLocation {
return SpaceLocation.defaultSpaceLocation(in: managedObjectContext!)
}
#objc var currentSpaceLocation: SpaceLocation {
get {
if _currentSpaceLocation == nil {
willChangeValue(for: \Document.currentSpaceLocation)
_currentSpaceLocation = defaultSpaceLocation
didChangeValue(for: \Document.currentSpaceLocation)
}
return _currentSpaceLocation!
}
set {
willChangeValue(for: \Document.currentSpaceLocation)
_currentSpaceLocation = newValue
didChangeValue(for: \Document.currentSpaceLocation)
}
}
and in SpaceLocation class as:
class func defaultSpaceLocation(in moc: NSManagedObjectContext) -> SpaceLocation {
let spaceLocationsRequest = NSFetchRequest<SpaceLocation>(entityName: "SpaceLocation")
var result:SpaceLocation? = nil
do {
let spaceLocations = try moc.fetch(spaceLocationsRequest)
result = spaceLocations.filter {$0.isBaseLocation}.first!
}
catch {
Swift.print("•••• ERROR ••••", #file, #function, "Couldn't get Default Location")
}
return result!
}
}
I access to currentSpaceLocation by:
(NSDocumentController.shared.currentDocument as?Document)?.currentSpaceLocation
but it works only if document is in foreground. When app goes background NSDocumentController.shared.currentDocument becomes nil so I cannot access document.currentSpaceLocation. Any idea how to solve this?