swift - 来自 JSON 的 Realm 数据库中的条目

标签 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 键执行存在性检查。如果存在这样的实体,请检查其基本参数以更新它,以防重要属性发生更改(例如名称(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)

最佳答案

我认为最好的方法是添加一个名为 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
    }
  }    
}

关于swift - 来自 JSON 的 Realm 数据库中的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50675499/

相关文章:

ios - 从 SwiftyJSON block 访问值时遇到问题

c# - 在哪里存储可编辑的配置参数

c++ - 将注册表访问转换为来自 MFC 功能包的数据库调用

swift - 使用 Decodable 的 Realm 快速列表

swift - 如何在 Realm 中建模 3 个模型之间的关系?

ios - 创建自定义 VoiceOver 转子以垂直导航 UICollectionView

swift - 如何保持 AVMIDIPlayer 播放?

ios - Realm iOS 教程,从头开始构建 iOS 应用程序,写入失败

macos - 使用字典查找和强制转换可选绑定(bind)时出现 Swift 编译器错误

Java - 从 SQL 数据库读取时遇到问题