2016-09-16 36 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