Good morning all, I am using Swift "new for me" and core data I am trying to fetch my stored UIIMage from core data the following way. FYI it is saved as Binary Data in core. And I can see the data if I NSLog it. My Fetch Request looks like this. I have NO ERRORS but my image is not showing.
When I save to Core Data the NSLog looks like this..
Did I get to Save Image
2015-10-12 09:05:43.307 Car-Doc-Safe-Plus[13972:3524049] The NewImage has this in it (entity: Documents; id: 0x7fd4c0432060 ; data: {
autoClub = nil;
driverLicense = <89504e47 0d0a1a0a 0000000d 49484452 00000215 00000155 08020000 00d7368a d8000000 01735247 4200aece 1ce90000 001c>;
insuranceID = nil;
noteText = nil;
plate = nil;
registration = nil;
})
But when i Fetch it looks like this..
The Request has this in it (entity: Documents; predicate: ((null)); sortDescriptors: ((null)); type: NSManagedObjectResultType; )
**override func viewDidLoad() {
super.viewDidLoad()
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext!
let request = NSFetchRequest(entityName: "Documents")
request.returnsObjectsAsFaults = false;
let results : NSArray
try! results = context.executeFetchRequest(request)
if results.count > 0 {
let res = results[0] as! NSManagedObject
carImageView.image = res.valueForKey("driverLicense")as? UIImage
}
}**
I know I am missing something but I cannot figure it out. Any help is greatly appreciated.
JZ
The "binary data" type in Core Data is intended for reading and writing NSData objects. Since you want to read/write UIImage, you need to use the "transformable" type. With transformable, Core Data will attempt to use NSCoding to encode/decode the data, converting it to/from NSData as needed (Swift as? will not do this). Since UIImage conforms to NSCoding, you don't need to do any extra work except to tell Core Data to convert the data.
Related
my code is like these:
//save to core data
func addPaper(){
let paper = Paper(context: self.context)
paper.id = UUID()
paper.subject = self.subject
paper.score = Float(self.score) ?? 0
paper.title = self.title
let imgs = try? NSKeyedArchiver.archivedData(withRootObject: self.images, requiringSecureCoding: true)
paper.images = imgs
try? self.context.save()
}
//retrieve to [UIImage]
let imgs = NSKeyedUnarchiver.unarchivedObject(ofClass: [UIImage], from: paper.images!)
there is an error tip:Static method 'unarchivedObject(ofClass:from:)' requires that '[UIImage]' conform to 'NSCoding'
I don't know what to do next, can anyone give me some help?
You should not store image in CoreData. Maybe store in base64 format, and you can encode/decode whenever you want.
Base64 To image:
func base64ToImage(data: String) -> Data{
let encodedImageData = data
let imageData = Data(base64Encoded: encodedImageData)
return imageData!
}
imageView.image = UIImage(data: dataDecoded)
Image to base64
func imageToBase64(image: UIImage) -> String {
return image.pngData()!
.base64EncodedString()
}
maybe you need this, any object can be saved to core data.
:https://stackoverflow.com/questions/56453857/how-to-save-existing-objects-to-core-data
I copied the following steps from others, hope it helps
1.making your custom types (Exercise) subclass of NSObject
2.setting the attribute's type in the core data model to Transformable
3.setting the CustomClass to [Exercise]
I'm adding objects to an NSMutableArray and archiving it with NSKeyedArchiver and UserDefaults.
Objects are added to the array, which I can see from the log console. I can also see that the archived objects contains the object.
The problem is that I whenever I unarchive the objects and add them to the mutable array, it always returns 1, no matter how many object I add.
Here's what I got:
Save objects to the array
trackNumberOfQuestionPlayed.add(questionsArray[randomQuestion] as AnyObject)
let saveQuestionsPlayed = NSKeyedArchiver.archivedData(withRootObject: trackNumberOfQuestionPlayed)
UserDefaults.standard.set(saveQuestionsPlayed, forKey: "QuestionsPlayed")
UserDefaults.standard.synchronize()
print(UserDefaults.standard.object(forKey: "QuestionsPlayed"))
Retrieve the objects
if let data = UserDefaults.standard.object(forKey: "QuestionsPlayed") as? Data {
if let trackNumberOfQuestionPlayed = (NSKeyedUnarchiver.unarchiveObject(with: data) as? NSMutableArray)
{
// In here you can access your array
print("Number of questions array is NOT empty: \(trackNumberOfQuestionPlayed.count)")
}
}
OK, I'm answering my own question. It turns out with a little bit tweaking you can save an array as described in my question. It turned out that some other code in my quiz game made a mess of it all. Sorted it out, and now the code below works:
Save objects to the array
trackNumberOfQuestionPlayed.add(questionsArray[randomQuestion] as AnyObject)
let saveQuestionsPlayed = NSKeyedArchiver.archivedData(withRootObject: trackNumberOfQuestionPlayed)
UserDefaults.standard.set(saveQuestionsPlayed, forKey: "QuestionsPlayed")
UserDefaults.standard.synchronize()
print("Count: \(trackNumberOfQuestionPlayed.count)")
Retrieve the objects
if let data = UserDefaults.standard.object(forKey: "QuestionsPlayed") as? Data {
if let trackNumberOfQuestionPlayed = (NSKeyedUnarchiver.unarchiveObject(with: data) as? NSMutableArray)
{
// In here you can access your array
self.trackNumberOfQuestionPlayed = trackNumberOfQuestionPlayed
print("Number of questions array is NOT empty: \(trackNumberOfQuestionPlayed.count)")
}
} else {
trackNumberOfQuestionPlayed = NSMutableArray()
print("questionsplayed is empty")
}
Saving NSMutableArray with NSUserDefaults in Swift Returns Nil
setObject method removed my codes like that and not work. i try all set types still not work. Any idead ?
var banksAccount : NSMutableArray = []
for bankJson in (self.users?[0].Banks)! {
self.banksAccount.add(bankJson)
}
UserDefaults.standard.set(self.banksAccount, forKey: "myBanksAccounts")
UserDefaults.standard.synchronize()
For saving
let cacheArrayData = NSKeyedArchiver.archivedData(withRootObject: banksAccount)
UserDefaults.standard.set(cacheArrayData, forKey: "EventItems")
For retrieving
let retriveArrayData = UserDefaults.standard.object(forKey: "EventItems") as? NSData
let retriveArray = NSKeyedUnarchiver.unarchiveObject(with: retriveArrayData! as Data) as? NSArray
self.eventsArray = NSMutableArray(array:retriveArray!)
Using swift 3.0, I'm trying to add an array of objects into user defaults. As this isn't one of the regular UserDefault types I've realised that the object or array of objects (can't work out which one) will need to be parsed to the type NSData to then be added to UserDefaults.
My attempt so far is the following:
Within the object
func updateDefaults()
{
let data = NSData(data: MyVariables.arrayList)
UserDefaults.standard.set(data, forKey: "ArrayList")
}
Where MyVariables.arrayList is the array of objects.
Lastly, if possible it would be nice to know how to retrieve this from UserDefaults and convert it to the original one-dimensional array of objects.
Thanks
REPOSITORY: https://github.com/Clisbo/ModularProject
You can't save your custom array in NSUserDefaults. To do that you should change them to NSData then save it in NSUserDefaults Here is the code.
var custemArray: [yourArrayType] {
get {
if let data = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as? NSData {
let myItem = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? yourType
}
}
set {
let data =NSKeyedArchiver.archivedDataWithRootObject(yourObject);
NSUserDefaults.standardUserDefaults().setObject(data, forKey: "yourKey")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
Im trying to put fetched objects into an Array, but I'm lost here... Any help would be greatly appreciated! I have an Entity with an attribute 'date' which is a NSDate type. The other attributes are NSNUmber types. I want to put all 'dates' into an array that I will use for a UIPicker, but I'm unable to cast NSArray to a Swift Array. Please see the code below:
var context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var request = NSFetchRequest(entityName: "Diary")
request.returnsObjectsAsFaults = false
//Fetching Data
do {
self.DataArray = try context.executeFetchRequest(request) as! [Diary]
} catch {
print("error")
}
var DATES = (self.DataArray as NSArray).valueForKey("date") as! NSArray
print(DATES) // all content is visible
months = DATES as! [String] // here the app crashes with error in the console - months = ([String]!) nil
I have an Entity with an attribute 'date' which is a NSDate type
So why are you trying to as! it into a String. A date is not a string. This should be [NSDate], not [String].