Why does function setValues do not change values of NSManaged object of type Phone? - swift

I created structure PhoneStructure. It should contain values from NSManaged object of CoreData entity Phone.
It has two function:
Function that gets values from Phone to save them in PhoneStructure(getValues) and function that gets value PhoneStructure to save them in Phone(setValues). However set function doesn't change values of Phone:
struct GenderStructure: Setable {
var status: String?
func setValues<T: NSManagedObject>(of object: T){
guard let gender = object as? Gender else { return }
gender.setValue(status, forKey: "status")
}
mutating func getValues<T: NSManagedObject>(from object: T){
guard let gender = object as? Gender else { return }
self.status = gender.status
}
At the same time, somehow setValues function of LocationStructure works although it is the same function, but which works with different entity(Location)
struct LocationStructure: Named{
var name: String?
var longitude: Double
var latitude: Double
init() {
name = nil
longitude = 0
latitude = 0
}
init(name: String, longitude: Double, latitude: Double){
self.name = name
self.longitude = longitude
self.latitude = latitude
}
func setValues<T: NSManagedObject>(of object: T){
guard let location = object as? Location else { return }
location.setValue(name, forKey: "name")
location.setValue(longitude, forKey: "longitude")
location.setValue(latitude, forKey: "latitude")
}
mutating func getValues<T: NSManagedObject>(from object: T){
guard let location = object as? Location else { return }
self.name = location.name
self.longitude = location.longitude
self.latitude = location.latitude
}

Related

SwiftUI async data receive from #escaping closure

I am having trouble with working over data I receive from server.
Each time server sends data it is new coordinates for each user. I am looping over each incoming data, and I want to send the data in completion to receive them on other end. And update model class with them. At the moment I have two users in server. And sometimes the closure passes data two times, but sometimes just one. And interesting thing is that class properties are not updated, at least I dont see them on UI.
This is function I call when data is received. Response is just string I split to get user data.
func updateUserAdrress(response: String, completion: #escaping (Int, Double, Double, String) -> Void){
var data = response.components(separatedBy: "\n")
data.removeLast()
data.forEach { part in
let components = part.components(separatedBy: ",")
let userID = components[0].components(separatedBy: " ")
let id = Int(userID[1])
let latitude = Double(components[1])!
let longitude = Double(components[2])!
let location = CLLocation(latitude: latitude, longitude: longitude)
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
if error == nil {
let placemark = placemarks?[0]
if let thoroughfare = placemark?.thoroughfare, let subThoroughfare = placemark?.subThoroughfare {
let collectedAddress = thoroughfare + " " + subThoroughfare
DispatchQueue.main.async {
completion(id!, latitude, longitude, collectedAddress)
}
}
} else {
print("Could not get address \(error!.localizedDescription)")
}
}
}
}
In this function I try to invoke the changes on objects. As the incoming data from server is different the first time I have splited the functionality, so the correct block of code would be called.
func collectUsers(_ response: String){
if users.count != 0{
updateUserAdrress(response: response) { id, latitude, longitude, address in
if let index = self.users.firstIndex(where: { $0.id == id }){
let user = self.users[index]
user.latitude = latitude
user.longitude = longitude
user.address = address
}
}
}else{
var userData = response.components(separatedBy: ";")
userData.removeLast()
let users = userData.compactMap { userString -> User? in
let userProperties = userString.components(separatedBy: ",")
var idPart = userProperties[0].components(separatedBy: " ")
if idPart.count == 2{
idPart.removeFirst()
}
guard userProperties.count == 5 else { return nil }
guard let id = Int(idPart[0]),
let latitude = Double(userProperties[3]),
let longitude = Double(userProperties[4]) else { return nil }
let collectedUser = User(id: id, name: userProperties[1], image: userProperties[2], latitude: latitude, longitude: longitude)
return collectedUser
}
DispatchQueue.main.async {
self.users = users
}
}
}
As I also need user address when app starts in model I have made simular function to call in init so it would get address for user. That seems to be working fine. But for more context I will add the model to.
class User: Identifiable {
var id: Int
let name: String
let image: String
var latitude: Double
var longitude: Double
var address: String = ""
init(id: Int, name: String, image: String, latitude: Double, longitude: Double){
self.id = id
self.name = name
self.image = image
self.latitude = latitude
self.longitude = longitude
getAddress(latitude: latitude, longitude: longitude) { address in
self.address = address
}
}
func getAddress(latitude: Double, longitude: Double, completion: #escaping (String) -> Void){
let location = CLLocation(latitude: latitude, longitude: longitude)
let geocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(location) { (placemarks, error) in
if error == nil {
let placemark = placemarks?[0]
if let thoroughfare = placemark?.thoroughfare, let subThoroughfare = placemark?.subThoroughfare {
let collectedAddress = thoroughfare + " " + subThoroughfare
completion(collectedAddress)
}
} else {
print("Could not get address \(error!.localizedDescription)")
}
}
}
}
And one interesting thing. That when closure receives two times data and I assign them to class, there are no changes on UI.
I made this project on Xcode 13.4.1 because on Xcode 14 there is a bug on MapAnnotations throwing purple warnings on view changes.

Swift Core Data Storing Custom Class return nil

I want to store Arrays with custom Objects to Core Data. I want to store two arrays with custom Classes. The first would be checkpoints as Array<[Checkpoint]> and the second one would be track as Array . Here's the Data Model: Data Model
import Foundation
import CoreData
public class Checkpoint: NSObject, NSCoding {
public static var supportsSecureCoding = true
public var longitude:Double?
public var latitude:Double?
public var instruction:String?
public var tts:Bool?
public var len_track:Int?
init(longitude: Double, latitude: Double, instruction: String, tts: Bool, len_track: Int) {
self.longitude = longitude
self.latitude = latitude
self.instruction = instruction
self.tts = tts
self.len_track = len_track
}
public func encode(with coder: NSCoder) {
coder.encode(longitude, forKey: "longitude")
coder.encode(latitude, forKey: "latitude")
coder.encode(instruction, forKey: "instruction")
coder.encode(tts, forKey: "tts")
coder.encode(len_track, forKey: "len_track")
}
public required init?(coder: NSCoder) {
guard let longitude = coder.decodeObject(forKey: "longitude") as? Double,
let latitude = coder.decodeObject(forKey: "latitude") as? Double,
let instruction = coder.decodeObject(forKey: "instruction") as? String,
let tts = coder.decodeObject(forKey: "tts") as? Bool,
let len_track = coder.decodeObject(forKey: "len_track") as? Int else {
return nil
}
self.longitude = longitude
self.latitude = latitude
self.instruction = instruction
self.tts = tts
self.len_track = len_track
}
}
public class Coordinates: NSObject, NSCoding {
public static var supportsSecureCoding = true
var latitude: Float?
var longitude: Float?
init(longitude: Float, latitude: Float) {
self.longitude = longitude
self.latitude = latitude
}
public func encode(with coder: NSCoder) {
coder.encode(longitude, forKey: "longitude")
coder.encode(latitude, forKey: "latitude")
}
public required init?(coder: NSCoder) {
guard let longitude = coder.decodeObject(forKey: "longitude") as? Float,
let latitude = coder.decodeObject(forKey: "latitude") as? Float else {
return nil
}
self.longitude = longitude
self.latitude = latitude
}
}
Apart from the two Transformable Entities, everything can be stored normally. But when I add checkpoints and track to a route, I get the following error:
Thread 1: "*** -decodeObjectForKey: cannot be sent to an abstract object of class NSCoder: Create a concrete instance!"

Firebase data and unexpected nil

My ultimate goal is to display annotations on a Map from MapKit. However, loading data from firebase does not work.
Here is the code:
var hotels = [Hotel]()
override func viewDidLoad() {
super.viewDidLoad()
map.delegate = self
checkLocationServices()
observe()
}
The function observe is the following:
func observe() {
Data().getAllHotel { (hotelA) -> (Void) in
if let hotel = hotelA {
print("hotel: ", hotel)
self.hotels.append(hotel)
let hotelAnnotation = MKPointAnnotation()
hotelAnnotation.title = "\(hotel.hotelName)"
hotelAnnotation.coordinate = CLLocationCoordinate2D(latitude: hotel.latitude, longitude: hotel.longitude)
self.map.addAnnotation(hotelAnnotation)
}
}
}
Note that the print in the if statement is not empty.
However the line hotelAnnotation.title causes a bug unexpected nil and I don't understand why.
Additionnally here is the getAllHotel function inside the Data class:
func getAllHotel(closure: HotelClosure?) {
let ref = Ref().databaseHotels
ref.observe(.childAdded) { (snapshot) in
if let dict = snapshot.value as? Dictionary<String, AnyObject> {
let hotel = self.fromDictToHotel(key: snapshot.key, dict: dict)
closure?(hotel)
} else {
closure?(nil)
}
}
}
func fromDictToHotel(key: String, dict: Dictionary<String, AnyObject>) -> Hotel? {
guard let hotelName = dict["name"] as? String else { return nil }
guard let latitude = dict["latitude"] as? Double else { return nil }
guard let longitude = dict["longitude"] as? Double else { return nil }
let hotelDescription = dict["description"] as? String
let hotelGrade = dict["grade"] as? Double
let hotelImageUrl = dict["hotelImageUrl"] as? String
let hotel = Hotel(hid: key, hotelName: hotelName, hotelDescription: hotelDescription, latitude: latitude, longitude: longitude, grade: hotelGrade, url: hotelImageUrl)
return hotel
}
Thanks in advance for your help!

unexpectedly found nil unexpectedly - struct init? not working

I am working on a demo app to return a list of restaurant with the google places API.
I have a Restaurant class - 1 property is a custom type RestaurantDetails. This is where the challenge is:
Restaurant.swift
class Restaurant {
var id:String
var placeId:String
var name:String
var location: Location //Location + address + coordinate + distance
var phone:String?
let details : RestaurantDetails
init(id:String, placeId:String, name:String, location: Location, details: RestaurantDetails) {
self.id = id
self.placeId = placeId
self.name = name
self.location = location
self.details = details
}
convenience init(dict:[String:Any]) {
let id = dict["id"] as! String
let placeId = dict["place_id"] as! String
let name = dict["name"] as! String
let address = dict["formatted_address"] as? String
let location = Location(address: address!, json: dict["geometry"] as! [String : Any])
if let price = dict["price_level"] as? Double {
print("price => \(Price(valueDouble: price))")
}
if let rating = dict["rating"] as? Double {
print("rating => \(Rating(valueDouble: rating))")
}
self.init(id: id, placeId: placeId, name: name, location: location!, details: RestaurantDetails(json: dict)!)
}
}
the initialization of the details property fails each time
even using the breakpoint does not help to debug the error because the custom init? does not seem to fire. I do not see any syntax error though
I am usually using guard let control flow to parse the JSON format if the value exists. unsuccessful.
the breakpoint does not kick in on the RestaurantDetails.swift file
RestaurantDetails.swift
enum Price {
case cheap, expensive, `default`
init(valueDouble: Double) {
switch valueDouble {
case 0..<2: self = .cheap
case 2..<4 : self = .expensive
default: self = .default
}
}
var dollarSymbol : String {
switch self {
case .cheap: return "$"
case .expensive: return "$$"
default: return ""
}
}
}
enum Rating {
case low, fair, good, excellent, `default`
init(valueDouble: Double) {
switch valueDouble {
case 0..<2: self = .low
case 3..<4: self = .fair
case 4..<5: self = .good
case 6 : self = .excellent
default: self = .default
}
}
var starSymbol : String {
switch self {
case .low: return "⭐"
case .fair: return "⭐⭐"
case .good: return "⭐⭐⭐"
case .excellent: return "⭐⭐⭐⭐"
default: return ""
}
}
}
struct RestaurantDetails {
let price:Price
let rating:Rating // Rating (enum) (filter)
let openNow: Bool //(filter)
let types : [String]?
let photos : [NSDictionary]?
}
extension RestaurantDetails {
init?(json: [String: Any]) {
guard let price = json["price_level"] as? Double,
let rating = json["rating"] as? Double,
let openingHours = json["opening_hours"] as? NSDictionary,
let types = json["types"] as? [String],
let photos = json["photos"] as? [NSDictionary] else {
return nil
}
print("json details : \(json)")
self.price = Price(valueDouble: price)
self.rating = Rating(valueDouble: rating)
self.openNow = openingHours["open_now"] as! Bool != nil ?? false
self.types = types
self.photos = photos
}
}
I also have a Location.swift file that works perfectly
struct Location {
var address :String
var coordinate:(lat:Double, lng:Double)
}
extension Location {
init?(address: String, json:[String:Any]) {
guard let latitude = json["location"] as? NSDictionary, let longitude = json["location"] as? NSDictionary else { return nil }
self.init(address: address, coordinate: (lat: latitude["lat"] as! Double, lng: longitude["lng"] as! Double))
}
}
As vadian described in his comment, the issue causing the crash is that location has a failable initializer, you are forcibly unwrapping it, and since initialization is in fact failing, you have now force-unwrapped a nil value.
The broader questions are: what do you, the developer, want to happen when some or all location data is not available, and what is the best way to go about doing that?
Options for handling incomplete or missing location data
Based on your description of the problem (“a demo app to return a list of restaurant with the google places api”), it is not clear whether or not restaurants without useable location data should enter your model. It is also not clear whether or not there is some location data you could do without. So I see three options:
Discard all restaurants with incomplete location data
Discard some restaurants with incomplete location data while keeping others
Keep all restaurants regardless of location data
To implement these options, you may want to use some common tools for dealing with optionals:
Nil-coalescing operator
a = b ?? c
Set a equal to b, unless b is nil, in which case set a equal to c.
Optional binding in guard and if
guard let a = b else { return }
Set a equal to b unless b is nil, in which case return from the current context. You can do work in the else branch prior to returning.
if let a = b { /* Do work using a */ } else { /* Do other work */ }
If b is not nil, enter the if branch and set a equal to b; if b is nil, enter the else branch.
How to do it
Discard all restaurants with incomplete location data
In this case, you could make a failable initializer for Restaurant, guarded by location being non-nil:
/// Initialization fails if `location` is `nil`
convenience init?(id:String, placeId:String, name:String, location: Location?, details: RestaurantDetails) {
guard let location = location else { return nil }
self.init(id: id, placeId: placeId, name: name, location: location, details: details)
}
Discard some restaurants with incomplete location data while keeping others
You may be able to recover from some kinds of missing location data. For example, it may be the case that you really just need the street address string and the latitude and longitude are inessential. You could rewrite your Location struct to reflect that:
struct Location {
var address: String
var coordinate: (lat: Double, lng: Double)?
}
extension Location {
init?(address: String, json:[String:Any]) {
let coordinate: (Double, Double)?
if let latitude = json["location"] as? NSDictionary, let longitude = json["location"] as? NSDictionary {
coordinate = (latitude, longitude)
} else {
coordinate = nil
}
self.init(address: address, coordinate: coordinate)
}
}
Alternative, lat/long might be the important part, but it might sometimes be possible to recover them from the street address using another API:
struct Location {
var address: String
var coordinate: (lat: Double, lng: Double)
}
extension Location {
init?(address: String, json:[String:Any]) {
let coordinate: (Double, Double)?
if let latitude = json["location"] as? NSDictionary, let longitude = json["location"] as? NSDictionary {
coordinate = (latitude, longitude)
} else {
/* An API call that takes an address string and tries to return lat/long but might return nil */
coordinate = returnedCoordinateFromAPI
}
guard let coordinate = coordinate else { return nil }
self.init(address: address, coordinate: coordinate)
}
}
Keep all restaurants regardless of location data
This is the easiest case. If location is not essential, make it optional:
class Restaurant {
var id: String
var placeId: String
var name: String
var location: Location? //Location + address + coordinate + distance
var phone: String?
let details: RestaurantDetails
init(id:String, placeId:String, name:String, location: Location?, details: RestaurantDetails) {
self.id = id
self.placeId = placeId
self.name = name
self.location = location
self.details = details
}
convenience init?(dict:[String:Any]) {
guard let id = dict["id"] as? String,
let placeId = dict["place_id"] as? String,
let name = dict["name"] as? String else { return nil }
// Use the address from the dictionary unless it is nil, in which case substitute an empty string
let address = dict["formatted_address"] as? String ?? ""
let location = Location(address: address, json: dict["geometry"] as? [String : Any])
if let price = dict["price_level"] as? Double {
print("price => \(Price(valueDouble: price))")
}
if let rating = dict["rating"] as? Double {
print("rating => \(Rating(valueDouble: rating))")
}
guard let details = RestaurantDetails(json: dict) else { return nil }
self.init(id: id, placeId: placeId, name: name, location: location, details: details)
}
}

possible to cast this Alamofire result to an array of dictionaries

I am not an iOS dev and have to make a few changes to a Swift / AlamoFire project (not mine) and am a bit lost.
I have the following JSON:
{"metro_locations":
[
{
"name":"Ruby Red"
},
{
"name":"Blue Ocean"
}
]
}
class (I know that there are issues here):
class Location{
var name=""
init(obj:tmp){
self.name=tmp["name"]
}
}
and need to make an AlamoFire call
Alamofire.request(.GET, "https://www.domain.com/arc/v1/api/metro_areas/1", parameters: nil)
.responseJSON { response in
if let dataFromNetworking = response.result.value {
let metroLocations = dataFromNetworking["metro_locations"]
var locations: [Location]=[]
for tmp in metroLocations as! [Dictionary] { // <- not working, Generic Paramter 'Key' could not be inferred
let location=Location.init(obj: tmp)
locations.append(location)
}
}
}
I have included the error msg, the "not working" but feel that there are issues in other parts too (like expecting a dictionary in the initialization). What does the 'Key' could not be inferred mean and are there other changes I need to make?
edit #1
I have updated my Location to this to reflect your suggestion:
init?(dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] else { return nil }
guard let name = dictionary["name"] else { return nil }
guard let latitude = dictionary["latitude"] else { return nil }
guard let longitude = dictionary["longitude"] else { return nil }
self.name = name as! String
self.id = id as! Int
self.latitude = latitude as! Double
self.longitude = longitude as! Double
}
but I get the error:
Could not cast value of type 'NSNull' (0x10f387600) to 'NSNumber' (0x10f77f2a0).
like this:
I would think that the guard statement would prevent this. What am I missing?
You can cast metroLocations as an array of dictionaries, namely:
Array<Dictionary<String, String>>
Or, more concisely:
[[String: String]]
Thus:
if let dataFromNetworking = response.result.value {
guard let metroLocations = dataFromNetworking["metro_locations"] as? [[String: String]] else {
print("this was not an array of dictionaries where the values were all strings")
return
}
var locations = [Location]()
for dictionary in metroLocations {
if let location = Location(dictionary: dictionary) {
locations.append(location)
}
}
}
Where
class Location {
let name: String
init?(dictionary: [String: String]) {
guard let name = dictionary["name"] else { return nil }
self.name = name
}
}
Clearly, I used [[String: String]] to represent an array of dictionaries where the values were all strings, as in your example. If the values included objects other than strings (numbers, booleans, etc.), then you might use [[String: AnyObject]].
In your revision, you show us a more complete Location implementation. You should avoid as! forced casting, and instead us as? in the guard statements:
class Location {
let id: Int
let name: String
let latitude: Double
let longitude: Double
init?(dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] as? Int,
let name = dictionary["name"] as? String,
let latitude = dictionary["latitude"] as? Double,
let longitude = dictionary["longitude"] as? Double else {
return nil
}
self.name = name
self.id = id
self.latitude = latitude
self.longitude = longitude
}
}