pull details from local database - swift

I want to pull details from local database but when I do the necessary operations, it returns null as a result. I can't understand where I went wrong.
var chosenCar=""
var chosenCarId : UUID?
the arrays I created, I transfer data to these arrays, there is no problem with that, I did a test
if chosenCar != "" {
//core data
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "CarsInformation")
let idString = chosenCarId?.uuidString
fetchRequest.predicate = NSPredicate(format: "id = %#", idString!)
fetchRequest.returnsObjectsAsFaults = false
do {
let results = try context.fetch(fetchRequest)
if results.count > 0 {
for result in results as! [NSManagedObject] {
if let name = result.value(forKey: "models") as? String {
modelTextField.text = name
}
if let year = result.value(forKey: "year") as? Int {
yearTextField.text = String(year)
}
if let price = result.value(forKey: "price") as? Int {
priceTextField.text = String(price)
}
if let imageData = result.value(forKey: "image") as? Data {
let image = UIImage(data: imageData)
imageView.image = image
}
}
}
} catch{
print("error")
}
} else {
modelTextField.text = ""
priceTextField.text = ""
yearTextField.text = ""
}
After doing these operations, I can't get the result I want.

Related

DataCore Query relationship one to one

I am doing an app project in iOS, swift, UIKit and Core Data. I have 2 entities User and Rating in a relationship one to one, a user can have or not a rating ,but a rating must belong to and user. I want to add users ,add ratings and fetch ratings by user name.
import Foundation
import UIKit
import CoreData
class DataBaseHelper {
let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext
static var instance = DataBaseHelper()
static var userSet : User? = User()
func addRating(id : Int32, gym : Int32, room: Int32){
let rating = NSEntityDescription.insertNewObject(forEntityName: "Rating", into: context!) as! Rating
var u = User()
var fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
do{
let request = try context?.fetch(fetchRequest) as! User
if(request != nil){
u = request as! User
}
}catch{
}
rating.ratingID = id
rating.gym = gym
rating.room = room
do{
try context?.save()
}
catch{
print("Data not saved")
}
var r = Rating()
var fetchRequest2 = NSFetchRequest<NSFetchRequestResult>(entityName: "Rating")
do{
let req = try context?.fetch(fetchRequest2) as! [Rating]
if(req.count != 0){
let r = req.first as! Rating
}
}catch{
}
DataBaseHelper.userSet!.name = rating.ratingOfUser?.name!
DataBaseHelper.userSet!.name = u.name
rating.ratingOfUser?.name = DataBaseHelper.userSet!.name
try! context?.save()
}
func getRatings () -> [Rating]{
var rating = [Rating]()
let fReq = NSFetchRequest<NSFetchRequestResult>(entityName: "Rating")
do{
rating = try context?.fetch(fReq) as! [Rating]
}catch{
print("can not fetch any data")
}
return rating
}
func getRatingByUserName(name : String) -> Rating {
var rating = Rating()
let fReq = NSFetchRequest<NSFetchRequestResult>(entityName: "Rating")
fReq.predicate = NSPredicate(format: "name == %#", name)
fReq.fetchLimit = 1
do{
let ratingsSaved = try context?.fetch(fReq) as! [Rating]
if(ratingsSaved.count != 0){
rating = ratingsSaved.first as! Rating
}else{
print("data not found")
}
}catch{
}
return rating
}
func updateRating(user: String,room: Int32,gym: Int32){
var rating = Rating()
var fetchRequest = NSFetchRequest<NSManagedObject>.init(entityName: "Rating")
fetchRequest.predicate = NSPredicate(format: "name == %#", user)
do{
let ratingsSaved = try context?.fetch(fetchRequest)
if(ratingsSaved?.count != 0){
rating = ratingsSaved?.first as! Rating
rating.room = room
rating.gym = gym
try context?.save()
print("data update")
}
}catch{
}
}
func deleteRating(user: String){
var fetchRequest = NSFetchRequest<NSManagedObject>.init(entityName: "Rating")
fetchRequest.predicate = NSPredicate(format: "name == %#", user)
do{
let ratingsSaved = try context?.fetch(fetchRequest)
context?.delete(ratingsSaved?.first as! Rating)
try context?.save()
print("Data deleted")
}catch{
}
}
func addUser(name: String,email :String,password : String) {
let user = NSEntityDescription.insertNewObject(forEntityName: "User", into: context!) as! User
user.name = name
user.email = email
user.password = password
do{
print(try context?.save())
}
catch{
print("user not saved")
}
}
func getAllUsers() -> [User]
{
var users = [User]()
var fReq = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
do{
users = try context?.fetch(fReq) as! [User]
}catch{
print("can not fetch any data")
}
return users
}
func getUser(name: String) -> User{
var user = User()
let fReq = NSFetchRequest<NSFetchRequestResult>.init(entityName: "User")
fReq.predicate = NSPredicate(format: "name == %#", name)
fReq.fetchLimit = 1
do{
let usersSaved = try context?.fetch(fReq) as! [User]
if(usersSaved.count != 0){
user = usersSaved.first as! User
}else{
print("data not found")
}
}catch{
}
return user
}
}

How to fetch Images from CoreData correct?

this is the code how I save images in CoreData:
lazy var dataImage = profileIcon.jpegData(compressionQuality: 1.0)
//MARK: - Saving the Workout Image
func savePUValues() {
// Kontext Identifiziern
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
let context = appDelegate.persistentContainer.viewContext
let entityName = "PushUps" //Tabellenname im DatenModell
//Neuen Datensatz anlegen:
guard let newEntity = NSEntityDescription.entity(forEntityName: entityName, in: context)
else {
return
}
let newSet = NSManagedObject(entity: newEntity, insertInto: context)
let savingImage = dataImage
newSet.setValue(savingImage, forKey: "image")
// Datensatz speichern
do {
try context.save()
} catch {
print("An error appeared")
}
}
Now I want to fetch the image data and load it into a UITableView:
With this code:
func loadValues() -> [CellData] {
//Kontext identifizieren
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//Anfrage stellen
let context = appDelegate.persistentContainer.viewContext
let entityName = "PushUps"
//MARK: - Request
// Use a specific fetch request
let request = NSFetchRequest<PushUps>(entityName: entityName)
// add a sort descriptor to sort the items by highScore descending
request.sortDescriptors = [NSSortDescriptor(key: "count", ascending: false)]
do {
// results is an array of PushUps instances, no type cast needed
let results = try context.fetch(request)
for r in results {
if let result = r as? NSManagedObject {
let titletext = "\(count!) Push-Ups"
var cellTitleLabel = UILabel()
cellTitleLabel.text = titletext
let workoutImage = result.value(forKey: "image") as? UIImageView
print("Image was loaded into the array")
var Data1 = CellData(imageData: workoutImage ?? oImageView, titleData: cellTitleLabel)
print("Image: \(String(describing: workoutImage)), TitLe: \(cellTitleLabel) ")
cellDataArray.append(Data1)
}
}
} catch {
print(error)
}
return cellDataArray
}
The problem is that the it's loading the image as nil.
The console is giving me this back: "Image: nil, TitLe: <UILabel: 0x115f17980; frame = (0 0; 0 0); text = '0.0 Push-Ups'; userInteractionEnabled = NO; layer = <_UILabelLayer: 0x28249cfa0>> "
So where is the problem? What is wrong with my Code?
Thanks for your help!
The problem is that you are saving Data and trying to retrieve it as a UIImageView, which is doomed to failure:
lazy var dataImage = profileIcon.jpegData(compressionQuality: 1.0)
// Data
let savingImage = dataImage
newSet.setValue(savingImage, forKey: "image")
// still Data
// ---------------------
let workoutImage = result.value(forKey: "image") as? UIImageView
// UIImageView?????
However, don't save image data into Core Data in the first place. Save to disk and store the partial path (e.g. the file name).

Edit all records by ID (Swift 4, CoreData)

I have Int array with values
Example:
var SelectedCard = [Int] ()
[3, 1, 2]
Me need edit my all records by order
Im tried this but app crash
for item in 0...SelectedCard.count-1 {
let order = SelectedCard[item]
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Card")
fetchRequest.predicate = NSPredicate(format: "order == %#", order)
do {
if let fetchResults = try managedContext.fetch(fetchRequest) as? [Card] {
if fetchResults.count != 0 {
for index in 0...fetchResults.count-1 {
let managedObject = fetchResults[index]
managedObject.setValue("", forKey: "folderID")
}
appDelegate.saveContext()
}
}
} catch {
print(error)
}
}
self.tableView.reloadData()
Try changing the predicate to
NSPredicate(format: "order == \(order)")

how to get the array count if string is empty from nsdictionary?

this is my respone
{
activeFromDate = "01/01/2017";
terminateDate = “02/05/2019”;
}
{
activeFromDate = "01/01/2013";
terminateDate = "<null>";
}
{
activeFromDate = "01/01/2017";
terminateDate = "02/05/2018";
}
{
activeFromDate = "07/01/2012";
terminateDate = "<null>";
}
{
activeFromDate = "01/01/2017";
terminateDate = "02/05/2019";
}
this is my code
let answerArray = NSMutableArray()
for i in 0..<arr.count
{
let dict = Dictionary[i] as! NSDictionary
let name1 = dict.value(forKey:"terminateDate") as! String
if(name1 == "")
{
print (answerArray.add(dict))
}
}
this is my nsdictionary response
how to get array count if terminatedDate is null and terminatedDate is greater than today date?
I have created a sample to read json file placed in your project. and have integrated the code as per your requirement.
Json File
{"Status":"success","Data":[
{"activeFromDate":"01/01/2017","terminateDate":"02/05/2019"},
{"activeFromDate":"01/01/2013","terminateDate":null},
{"activeFromDate":"01/01/2017","terminateDate":"02/05/2018"},
{"activeFromDate":"07/01/2012","terminateDate":null},
{"activeFromDate":"01/01/2017","terminateDate":"02/05/2016"},
{"activeFromDate":"01/01/2017","terminateDate":"02/05/2019"}
]
}
In your View Controller
import UIKit
class HomeViewController: UIViewController {
let answerArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
jsonParsingFromFile()
}
func jsonParsingFromFile()
{
let path: NSString = Bundle.main.path(forResource: "tjw", ofType: "json")! as NSString
let data : NSData = try! NSData(contentsOfFile: path as String, options: NSData.ReadingOptions.dataReadingMapped)
self.startParsing(data: data)
}
func startParsing(data :NSData)
{
let dict: NSDictionary!=(try! JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers)) as? NSDictionary
//print(dict)
guard let dataArr:NSArray = dict.value(forKey: "Data") as? NSArray else {
return
}
print(dataArr.count)
for i in 0..<dataArr.count{
guard let currentDict:NSDictionary = dataArr[i] as? NSDictionary else {
return
}
let activeFromDateStr:String = currentDict.value(forKey: "activeFromDate") as? String ?? ""
let terminateDateStr:String = currentDict.value(forKey: "terminateDate") as? String ?? ""
print(activeFromDateStr, terminateDateStr)
if terminateDateStr != ""{
let date2 = convertToDate(dateStr: terminateDateStr)
let today = Date()
if date2>today{
answerArray.add(currentDict)
}
}else{
answerArray.add(currentDict)
}
}
print(answerArray)
}
func convertToDate(dateStr:String)->Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.locale = Locale(identifier: "en_IN")
let date = dateFormatter.date(from: dateStr)!
return date
}
}

How to separate values from an array using Swift 4

How to separate values from an array using Swift 4. Following are my data:
arrWeekly == (
{
date = "2018-04-30";
units = "g/dL";
value = 12;
},
{
date = "2017-06-27";
units = "g/dL";
value = "14.5";
}
)
My Code:
if let arrMonthly = dictPeriod["monthly"] as? [Any], arrMonthly.count > 0
{
self.arrMonth = NSMutableArray(array: arrMonthly)
print("arrMonthly == ",self.arrMonth)
}else{
self.arrMonth = NSMutableArray()
}
I want to separate both dates & Values.
if let arrMonthly = dictPeriod["monthly"] as? [[AnyHasahble:String]], ! arrMonthly.isEmpty {
for disc in arrMonthly{
if let date = disc["date"] as? String{
}
if let units = disc["units"] as? String{
}
if let value = disc["value"] as? String{
}
}
}else{
}
let dictPeriod = YOUR_DICTIONARY
guard let arrMonthly = dictPeriod["monthly"] as? [[String: Any]], !arrMonthly.isEmpty else { return }
let dateArr = arrMonthly.map({ $0["date"] as! String })
let unitsArr = arrMonthly.map({ $0["units"] as! String })
let valueArr = arrMonthly.map({ $0["value"] as! String })