使用Swift将JSON或CSV数据导入到Firestore

时间:2018-11-30 02:16:09

标签: ios swift firebase

似乎仍然无法将JSON或CSV文件直接导入到Firestore数据库。许多建议是针对不能很好地转换为Swift的基于JavaScript的应用程序的。有没有人有很好的Swift解决方案,可以使用JSON / CSV将数据添加到Firestore数据库中?

//example json
[
  {
    "name": "Stone Cove Marina Inc",
    "email": "NOT IN SAMPLE",
    "category": "Docks",
    "category2": "Marinas",
    "category3": "Dock Builders",
    "address": "134 Salt Pond Rd",
    "city": "Wakefield",
    "state": "RI",
    "zip": 2879,
    "phone": "(401) 783-8990",
    "website": "http://stonecovemarinari.com"
  },
  {
    "name": "Bluehaven Homes",
    "email": "NOT IN SAMPLE",
    "category": "General Contractors",
    "category2": "Home Builders",
    "category3": "",
    "address": "5701 Time Sq",
    "city": "Amarillo",
    "state": "TX",
    "zip": 79119,
    "phone": "(806) 452-2545",
    "website": "http://www.bluehavenhomes.com/"
  }
]

//here is the database structure
//collection is "businesses"; each "business" gets a document id; within each document id set the data

database.collection("businesses").document().setData(/*data here*/)

1 个答案:

答案 0 :(得分:0)

您可以尝试

let str = """

      [
      {
        "name": "Stone Cove Marina Inc",
        "email": "NOT IN SAMPLE",
        "category": "Docks",
        "category2": "Marinas",
        "category3": "Dock Builders",
        "address": "134 Salt Pond Rd",
        "city": "Wakefield",
        "state": "RI",
        "zip": 2879,
        "phone": "(401) 783-8990",
        "website": "http://stonecovemarinari.com"
      },
      {
        "name": "Bluehaven Homes",
        "email": "NOT IN SAMPLE",
        "category": "General Contractors",
        "category2": "Home Builders",
        "category3": "",
        "address": "5701 Time Sq",
        "city": "Amarillo",
        "state": "TX",
        "zip": 79119,
        "phone": "(806) 452-2545",
        "website": "http://www.bluehavenhomes.com/"
      }
    ]

"""

do {
    let json = try JSONSerialization.jsonObject(with:str.data(using:.utf8)!, options: []) as! [[String: Any]]
    for var i in 0...json.count - 1
    {
      database.collection("businesses").document().setData(json[i])
    }
} catch  {
    print(error)
}