2016-09-16 64 views
0

我想弄清楚如何从JSON中存储CoreData中的位置。 我使用此代码来从JSON API数据,并试图将其存储在我的CoreDataCoreData中的商店位置(Swift)

let appDelegate = UIApplication.shared.delegate as! AppDelegate 
let context = appDelegate.persistentContainer.viewContext 
let newPok = NSEntityDescription.insertNewObject(forEntityName: "Person", into: context) 

for jsonItem in json { 
    let item = jsonItem as! NSDictionary 

    let pokemonName = item["name"] 
    let pokemonDesc = item["description"] 
    let pokemonLat = (item["location"] as! NSDictionary) ["latitude"] 
    let pokemonLon = (item["location"] as! NSDictionary) ["longitude"] 

    let coordinates = CLLocationCoordinate2D(latitude: pokemonLat as! CLLocationDegrees, longitude: pokemonLon as! CLLocationDegrees) 

    let annotation = MKPointAnnotation() 

    annotation.title = pokemonName as! String? 
    annotation.subtitle = pokemonDesc as! String? 

    annotation.coordinate = coordinates 

    self.map.addAnnotation(annotation) 

    newPok.setValue(pokemonName as! String, forKey: "name") 
    newPok.setValue(pokemonDesc as! String, forKey: "desc") 
    newPok.setValue(pokemonLat as! String, forKey: "lat") 
    newPok.setValue(pokemonLon as! String, forKey: "lon") 

    do { 
     try context.save() 
    } catch { 
     print("not saved") 
    } 
} 

但是当我运行这段代码,我总是得到一个fatal exception

error Domain=NSCocoaErrorDomain Code=134190 "(null)" UserInfo={entity=Person, property=lat, reason=Source and destination attribute types are incompatible} 

我的数据库中有一个设置有4个字符串(名称,说明,纬度,经度)

有谁知道我在做什么错在这里?

亲切的问候,

约翰

+0

core-data中'lat'的类型? –

+0

类型是字符串。但我认为这是不正确的 – Johan

+0

虽然缩进...... o.0 – Fogmeister

回答

0

您需要纬度和龙属性的数据类型更改从StringInteger16

+0

谢谢你的回答!我是否需要将我的变量(pokemonlat,pokemonlon)转换为其他东西?或者字符串足够好 – Johan

+0

您必须将它们两个都从字符串转换为整数或数字 –

0

好吧,我想通了。

我将我的核心数据属性从string更改为double,并在我的代码中我做了pokemonLat as! Double?。这工作。

感谢您的帮助! appricate它!

+0

,只有在您100%确定服务器的JSON响应中包含纬度/经度自编号,而不是以字符串包装在引号中。否则你将会崩溃。 所以也许会更好地写这样的事情: let lat:Double? = dictionary [“lat”]。flatMap {Double($ 0)} –

+0

好的,谢谢你的建议! :) – Johan