save uiimageview to coredata as binary data swift (5) - core-data

I am trying to save a imageview as a image to binary data in core data. My code is not working. It has a compile error. In View controller it is not regisitering cdHandler. All i want to do is save the the imaveview as binary data in a core data model.I have 2 classes a app delegate and a view controller.
CLASS VIEW CONTROLLER
import UIKit
import CoreData
class ViewController: UIViewController {
var canVasView = UIImageView()
#objc func hhh() {
let photo = self.canVasView.image
let data = photo!.pngData()
if cdHandler.saveObject(pic: data!){
}
}
}
APP DELEGATE
import UIKit
import CoreData
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Model")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
class cdHandler: NSObject {
private class func getContext() -> NSManagedObjectContext {
let appdeleagetzz = UIApplication.shared.delegate as! AppDelegate
return appdeleagetzz.persistentContainer.viewContext
}
class func saveObject(pic: Data, userName: String) -> Bool {
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
let managedObject = NSManagedObject(entity: entity!, insertInto: context)
managedObject.setValue(pic, forKey:"pic")
managedObject.setValue(userName, forKey:"userName")
do {
try context.save()
return true
} catch {
return false
}
}
class func deletObject(user: User) -> Bool {
let context = getContext()
context.delete(user)
do {
try context.save()
return true
} catch {
return false
}
}
class func fetchObject() -> [User]? {
do {
let context = getContext()
return try context.fetch(User.fetchRequest())
} catch {
return [User]()
}
}
}
}

The error message, *Value of type 'AppDelegate' has no member named 'persistentContainer', explains the problem. Indeed, when I look at the code for your AppDelegate class, I can confirm that it has no member named 'persistentContainer'. (If I am reading it correctly, the last two lines in the file are closing curly brackets. The first one closes your cdHandler nested class, and the second one closes your AppDelegate class.)
Do the following exercise. In Xcode, click in the menu: File > New Project and select iOS, Application and Single View App. Name your new project Junk. Switch on the Core Data checkbox. Click button Create. After it is done, look at the AppDelegate.swift which Xcode created, and in the AppDelegate class, you see it contains 8 functions (func). The 7th one is lazy var persistentContainer. Aha! The compiler is telling you that you probably should not have deleted those 8 functions, persistentContainer in particular.
You should copy that persistentContainer func from that Junk project into your AppDelegate class in your real project. Or, to head off future trouble, consider copying most of the other 7 funcs also. As you can see, most of them don't do anything except provide comments with explanations that are useful for beginners. After you are done copying, close the Junk project. (I overwrite my Junk project with a new Junk project several times in a typical week, especially when answering StackOverflow questions.)
That should fix this particular error and answer this question. Onward to the next issue. :)
Response to comment that you still get the error with cdHandler
Having nothing else to go on, I presume that the error that you are referring to is the compiler error still in your screenshot. In other words, you are saying that adding the persistentContainer definition did not make it any better.
Well, it works for me. Please replace all of the code in your AppDelegate.swift class with the following, build and run it…
import UIKit
import CoreData
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
AppDelegate.cdHandler.testGetContext()
return true
}
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Junk")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
class cdHandler: NSObject {
private class func getContext() -> NSManagedObjectContext {
let appdeleagetzz = UIApplication.shared.delegate as! AppDelegate
return appdeleagetzz.persistentContainer.viewContext
}
class func testGetContext() {
let context = getContext()
print("getContext() succeeded, got \(context)")
}
class func saveObject(pic: Data, userName: String) -> Bool {
let context = getContext()
let entity = NSEntityDescription.entity(forEntityName: "User", in: context)
let managedObject = NSManagedObject(entity: entity!, insertInto: context)
managedObject.setValue(pic, forKey:"pic")
managedObject.setValue(userName, forKey:"userName")
do {
try context.save()
return true
} catch {
return false
}
}
class func deletObject(user: NSManagedObject) -> Bool {
let context = getContext()
context.delete(user)
do {
try context.save()
return true
} catch {
return false
}
}
}
}
You see that compiles with no errors. Also, it runs and the AppDelegate.cdhandler.getContext() method works. As you can see, in AppDelegate.application(application:didFinishLaunchingWithOptions:), I have added a call to a new method which I defined later,AppDelegate.cdHandler.testGetContext()`. It works perfectly.
Are you getting a different error now? If so, you need to specify whether it is a Build or Run error. In either case, copy and paste the text of the error into your question, and tell us where it occurs.

Related

When and how often should initializeCloudKitSchema be called?

I am using NSPersistentCloudKitContainer in my Application, and I am struggling to understand when and how often should I call the method initializeCloudKitSchema() of my container.
Do I understand correctly that this is something to use in development to update the development schema update in CloudKit backend?
Should my App in production, in hands of my user ever call this method?
Here is the code that I am using:
import CoreData
import Foundation
final class DataController: ObservableObject {
let container = NSPersistentCloudKitContainer(name: "MyAmazingSchema")
init() {
container.loadPersistentStores {
description, error in
if let error = error as NSError? {
fatalError("Core Data - Unresolved error \(error), \(error.userInfo)")
}
}
do {
// Should I do this ⬇️ in Production?
try container.initializeCloudKitSchema()
}
catch {
print(error)
}
container.viewContext.automaticallyMergesChangesFromParent = true
}
}

NSManagedObject inserted in context, but not shown in tableview

Using Core Data in my App, I have a strange behaviour. I can add and remove objects using FirstResponder, and the objects are shown immediately in my tableView.
But if I want to add Objects programmatically , objects are only registered and not saved - nor shown in the tableView.
What I did :
Creating the PersistentContainer
class ViewController: NSViewController {
#IBOutlet var arrayCrtl: NSArrayController!
var container: NSPersistentContainer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
container = NSPersistentContainer(name:"Document")
container.loadPersistentStores(completionHandler: { (storeDescription, error ) in
if let error = error { print ("\(error)") }
})
}
Then, programmatically adding a ManagedObject
let context = container.viewContext
let describer = NSEntityDescription.entity(forEntityName: "Event", in: context)!
let newEvent:Event = Event(entity:describer, insertInto:context)
container.viewContext.insert(newEvent)
print ( container.viewContext.registeredObjects)
Any idea what's missing ?
I simply forgot to set the ArrayController to "prepares content" in the attribute inspector:

WKWebview:Remove Copy,lookup,share button from Menu and show custom

I want to implement my custom MenuController once user selects a text. I am using the below code to do that, I subclassed WKWebview and implemented below
override init(frame: CGRect, configuration: WKWebViewConfiguration) {
super.init(frame: frame, configuration: WKWebViewConfiguration())
enableCustomMenu()
}
func enableCustomMenu() {
let menuController = UIMenuController.shared
let testmenu = UIMenuItem(title: "Test", action: #selector(test))
menuController.menuItems = [testmenu]
}
func test(){
var text = ""
self.evaluateJavaScript("document.getSelection().toString()") { (data, error) in
text = data as! String
}
print(text)
}
override func becomeFirstResponder() -> Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
switch action {
case #selector(test):
return true
default:
return false
}
}
This used to work fine for UIWebview, but in WKWebview, in the canPerformAction we are no longer getting copy, lookup and share actions so these guys are not getting removed.
I had this problem too, I found that you can customize your WKwebview by overriding the function canPerformAction
here is an article about it .
It worked for me!
Hope that help you.

MKAnnotationView RightCallOut button crashes my app when I click on it

I'm calling a service and returning a bunch of latitudes and longitudes which I'm then placing on a map using MapKit.
using MKAnnotationView I'm adding a RightCallOutButton to each annotation.
So I had to create a new MapDelegate. Code below.
If I click on the button I create the app crashes and I get an error from MonoTouch saying the selector is accings omething that has already been GC'd (garbage collected).
So my question would be, where should I set the RightCalloutAccessoryView and where should I create the button, if not in this code below?
public class MapDelegage : MKMapViewDelegate {
protected string _annotationIdentifier = "BasicAnnotation";
public override MKAnnotationView GetViewForAnnotation (MKMapView mapView, NSObject annotation) {
MKAnnotationView annotationView = mapView.DequeueReusableAnnotation(this._annotationIdentifier);
if(annotationView == null) {
annotationView = new MKPinAnnotationView(annotation, this._annotationIdentifier);
} else {
annotationView.Annotation = annotation;
}
annotationView.CanShowCallout = true;
(annotationView as MKPinAnnotationView).AnimatesDrop = true;
(annotationView as MKPinAnnotationView).PinColor = MKPinAnnotationColor.Green;
annotationView.Selected = true;
var button = UIButton.FromType(UIButtonType.DetailDisclosure);
button.TouchUpInside += (sender, e) => {
new UIAlertView("Testing", "Testing Message", null, "Close", null).Show ();
} ;
annotationView.RightCalloutAccessoryView = button;
return annotationView;
}
}
annotationView = new MKPinAnnotationView(annotation, this._annotationIdentifier);
...
var button = UIButton.FromType(UIButtonType.DetailDisclosure);
You should avoid declaring local variables to hold references you expect to outlive the method itself. Once there's no reference to annotationView or button the Garbage Collector (GC) is free to collect them (the managed part) even if it's native counterparts still exists. However when a callback to them is called you'll get a crash.
The easiest solution is to keep a list of them and (at the class level, i.e. a List<MKPinAnnotationView> field) clear the list when you destroy the view. The UIButton should not be necessary since there's a reference between the view and it.
NOTE: work is being done to hide this complexity from developers in future versions of MonoTouch. Sadly you cannot ignore such issues at the moment.

Where to implement CLLocationManager

I have an app with a tab bar and 3 tabs. The current location of the user is going to be needed to be known on any of the three tabs. Would the best place to implement CLLocationManager be in the app delegate in this case?
Is it ok (good practise?) to put the CLLocationManager delegate methods in the app delegate m file?
Where would you suggest i place the CLLocationManager as I'm going to be calling -startUpdatingLocation from any of the three tabs?
Thanks
The app delegate is a reasonable place to put it. Another option would be to create a custom singleton factory class that has a class method that returns your location manager delegate and implement the delegate methods there. That would keep your app delegate class cleaner.
Here's a skeleton singleton class implemention based off of Peter Hosey's "Singletons in Cocoa: Doing them wrong". This may be overkill, but it's a start. Add your delegate methods at the end.
static MyCLLocationManagerDelegate *sharedInstance = nil;
+ (void)initialize {
if (sharedInstance == nil)
sharedInstance = [[self alloc] init];
}
+ (id)sharedMyCLLocationManagerDelegate {
//Already set by +initialize.
return sharedInstance;
}
+ (id)allocWithZone:(NSZone*)zone {
//Usually already set by +initialize.
#synchronized(self) {
if (sharedInstance) {
//The caller expects to receive a new object, so implicitly retain it
//to balance out the eventual release message.
return [sharedInstance retain];
} else {
//When not already set, +initialize is our caller.
//It's creating the shared instance, let this go through.
return [super allocWithZone:zone];
}
}
}
- (id)init {
//If sharedInstance is nil, +initialize is our caller, so initialze the instance.
//If it is not nil, simply return the instance without re-initializing it.
if (sharedInstance == nil) {
if ((self = [super init])) {
//Initialize the instance here.
}
}
return self;
}
- (id)copyWithZone:(NSZone*)zone {
return self;
}
- (id)retain {
return self;
}
- (unsigned)retainCount {
return UINT_MAX; // denotes an object that cannot be released
}
- (void)release {
// do nothing
}
- (id)autorelease {
return self;
}
#pragma mark -
#pragma mark CLLLocationManagerDelegateMethods go here...
I simply included my LocationManager in my AppDelegate directly, since it added little code.
However if you are going to include your LocationManager in the AppDelegate, then you should consider using NSNotifications to alert your viewcontrollers of the location updates your AppDelegate receives.
See this link
Send and receive messages through NSNotificationCenter in Objective-C?

Resources