来自JSON

时间:2018-06-04 07:36:05

标签: swift database realm

对不起翻译(非常糟糕的英语)

这是来自服务器的JSON 你需要在课堂上写一切,教程没有帮助

{
"status": "string",
"exercises": [
{
  "id": 0,
  "uuid": "string",
  "name_ru": "string",
  "name_en": "string",
  "body_part": {
        "id": 0,
        "uuid": "string",
        "name_ru": "string",
        "name_en": "string"
  },
  "equipment": {
         "id": 0,
         "uuid": "string",
         "name_ru": "string",
         "name_en": "string"
  },
  "kind": {
        "id": 0,
        "uuid": "string",
        "name_ru": "string",
        "name_en": "string"
     }
   }
  ]
 }

有必要以新格式(添加UUID字段)实施练习。在来自服务器的每个练习中都有以下数据:肌肉群练习,练习类型,设备。这些实体中的每一个都必须本地存储在Realm数据库中,并且必须始终使用uuid键执行存在性检查。如果存在这样的实体,请检查其基本参数以更新它,以防重要属性发生更改(例如,name(nameRu))

import RealmSwift
import Foundation


@objcMembers class RealmExercise: Object {
let id = RealmOptional<Int>()
dynamic var uuid = ""
dynamic var nameRu = ""
dynamic var nameEn = ""
dynamic var kind: [Kind]?
dynamic var bodyPart: [BodyPart]?
dynamic var equipment: [Equipment]?

convenience init(nameRu: String, id: Int?, nameEn: String, uuid: String) {
    self.init()
    self.nameRu = nameRu
    self.id.value = id
    self.nameEn = nameEn
    self.uuid = uuid

}
    func idString() -> String? {
        guard let id = id.value else { return nil }
        return String(id)
    }
func create<T: Object>(_ object: T) {
    do {
        try realm?.write {
            realm?.add(object)
        }
    } catch {
        print("error create object")
    }
}
}

@objcMembers class Kind: Object {
dynamic var nameRu: String? = ""
dynamic var nameEn: String? = ""
let id = RealmOptional<Int>()
dynamic var uuid = ""
let exercise = List<RealmExercise>()

convenience init(nameRu: String?, id: Int?, nameEn: String?, uuid: String) {
    self.init()
    self.nameRu = nameRu
    self.id.value = id
    self.nameEn = nameEn
    self.uuid = uuid
}
func idString() -> String? {
    guard let id = id.value else { return nil }
    return String(id)
}
public func saveOrUpdate() {
    let realm = try! Realm()
    try! realm.write() {
        realm.add(self, update: true)
    }
}
}
@objcMembers class BodyPart: Object {
dynamic var nameRu: String? = ""
dynamic var nameEn: String? = ""
let id = RealmOptional<Int>()
dynamic var uuid = ""
let exercise = List<RealmExercise>()

convenience init(nameRu: String?, id: Int?, nameEn: String?, uuid: String) {
    self.init()
    self.nameRu = nameRu
    self.id.value = id
    self.nameEn = nameEn
    self.uuid = uuid
}
func idString() -> String? {
    guard let id = id.value else { return nil }
    return String(id)
}
public func saveOrUpdate() {
    let realm = try! Realm()
    try! realm.write() {
        realm.add(self, update: true)
    }
}
}
@objcMembers class Equipment: Object {
dynamic var nameRu: String? = ""
dynamic var nameEn: String? = ""
let id = RealmOptional<Int>()
dynamic var uuid = ""
let exercise = List<RealmExercise>()

convenience init(nameRu: String?, id: Int?, nameEn: String?, uuid: String) {
    self.init()
    self.nameRu = nameRu
    self.id.value = id
    self.nameEn = nameEn
    self.uuid = uuid
}
func idString() -> String? {
    guard let id = id.value else { return nil }
    return String(id)
}
public func saveOrUpdate() {
    let realm = try! Realm()
    try! realm.write() {
        realm.add(self, update: true)
    }
}
}

VievController

 var exercise: Results<RealmExercise>!
 let users = JSON.object(forKey: "exercises") as! [NSDictionary]


            let realm = try! Realm()
            users.forEach { userJSON in



                let saveExercise = RealmExercise.init(nameRu: userJSON.object(forKey: "name_ru") as! String, id: userJSON.object(forKey: "id") as? Int, nameEn: userJSON.object(forKey: "name_en") as! String, uuid: userJSON.object(forKey: "uuid") as! String)


                exercise = realm.objects(RealmExercise.self)

1 个答案:

答案 0 :(得分:0)

我认为这里最好的方法是添加一个名为SwiftyJSON的cocoapod,这使得解析JSON变得轻而易举。看看我的天气应用程序如何解析。

import UIKit
import CoreLocation
import Alamofire
import SwiftyJSON


class WeatherViewController: UIViewController, CLLocationManagerDelegate, ChangeCityDelegate {

//Constants
let WEATHER_URL = "http://api.openweathermap.org/data/2.5/weather"
let APP_ID = "8a5f77889dbdb03403fcdbfe3f053215"


//TODO: Declare instance variables here
let locationManager = CLLocationManager()
let weatherDataModel = WeatherDataModel()


//Pre-linked IBOutlets
@IBOutlet weak var weatherIcon: UIImageView!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()


    //TODO:Set up the location manager here.
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters // specify the accuracy for the coordinates
    locationManager.requestWhenInUseAuthorization() //you need to add to plist Privacy and request string
    locationManager.startUpdatingLocation()


}



//MARK: - Networking
/***************************************************************/

//Write the getWeatherData method here:
func getWeatherData(url: String, parameters: [String:String]){
    Alamofire.request(url, method: .get, parameters: parameters).responseJSON {
        response in
        if response.result.isSuccess{
            print("Success got the weather data")

            let weatherJSON: JSON = JSON(response.result.value!)
            print(weatherJSON)

            self.updateWeatherData(json: weatherJSON)

        } else {
            print("There is an error \(response.result.error ?? "NO ERROR WEIRD" as! Error)")
            self.cityLabel.text = "Connection issues"
        }
    }
}






//MARK: - JSON Parsing
/***************************************************************/


//Write the updateWeatherData method here:
func updateWeatherData(json: JSON) {
    if let tempResult = json["main"]["temp"].double {

    weatherDataModel.temperature = Int(tempResult - 273.15)

    weatherDataModel.city = json["name"].stringValue

    weatherDataModel.condition = json["weather"][0]["id"].intValue

    weatherDataModel.weatherIconName = weatherDataModel.updateWeatherIcon(condition: weatherDataModel.condition)

    updateUIWithWeatherData()

    } else {
        cityLabel.text = "Weather unavailable :("
    }
}



//MARK: - UI Updates
/***************************************************************/


//Write the updateUIWithWeatherData method here:
func updateUIWithWeatherData(){
    temperatureLabel.text = "\(weatherDataModel.temperature)℃"
    cityLabel.text = weatherDataModel.city
    weatherIcon.image = UIImage(named: weatherDataModel.weatherIconName)
}





//MARK: - Location Manager Delegate Methods
/***************************************************************/


//Write the didUpdateLocations method here:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[locations.count - 1]
    if location.horizontalAccuracy > 0 { //if it is below zero it is invalid this is why we check this
        locationManager.stopUpdatingLocation()
        locationManager.delegate = nil

        print("Latitude: \(location.coordinate.latitude) Logitude: \(location.coordinate.longitude)")
        let latitude = String(location.coordinate.latitude)
        let longitude = String(location.coordinate.longitude)
        let params: [String : String] = ["lat":latitude, "lon":longitude, "appid":APP_ID]
        getWeatherData(url: WEATHER_URL, parameters: params)
    }
}


//Write the didFailWithError method here:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
    cityLabel.text = "Location unavailable!"

}




//MARK: - Change City Delegate methods
/***************************************************************/


//Write the userEnteredANewCityName Delegate method here:
func userEnteredANewCityName(city: String) {
    print(city)

    let params: [String : String] = ["q" : city, "appid" : APP_ID]
    getWeatherData(url: WEATHER_URL, parameters: params)
}


//Write the PrepareForSegue Method here
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "changeCityName" {
        let destinationVC = segue.destination as! ChangeCityViewController
        destinationVC.delegate = self //we are setting the ChangeCityViewController's delegate to be this View Controller which is WeatheViewController
    }
  }    
}