这是一个简单的问题。我不知道(也不能自己弄清楚)正确的术语是用于“编辑”从JSON代码接收的数据。这里是我当前的代码:Swift 3&JSON - 如何编辑从数据库接收的数据?
// Create a url and a session to load it in the background.
let url = URL(string: "http://api.fixer.io/latest")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil {
// Try to extract some content from the data.
if let content = data {
do {
// Try to create an array out of the extracted data content.
let jsonResult = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
// Search for specific objects in the array.
if let rates = jsonResult["rates"] as? NSDictionary {
print("Rates: \(rates)\n\n")
if let currency = rates["USD"] {
// Output of line below is – "Currency: \"1.0893\""
print("Currency: \(currency)")
}
}
} catch {
print("Error deserializing the JSON:\n\(String(describing: error))")
}
}
} else {
print("Error creating the URLSession:\n\(String(describing: error))")
}
}
// Begin using the URLSession to extract the data.
task.resume()
正如你可以在上面看到,我从一个URL使用JSON得到一些数据,然后提取特定的数据集,我正在加标题rates
和currency
。
但是,我无法在Web上的任何地方找到编辑数据的方法。例如:假设我想将currency
的值改为等于“$ 230”而不是“1.0893”。什么是必要的术语/代码去改变它?另一个例子是,如果我想添加另一个对象到rates
词典。如果我想添加或类似的东西呢?我不懂这方面的具体语法。我需要帮助!
编辑 - 是的,我试图改变数据库本身,这种方式,当信息从它后面拉,这是随着我现在做的更改而更新。在我上面的例子中,我说我可以将currency
更改为“230美元”。那么,我希望它永久保留在数据库中,这样当我稍后提取它的值时,而不是仍然是“1.0893”,现在它是我改变它的值。
这个词是“推?”吗?我想对数据库本身进行更改。
如果您从URL获取数据,则需要将修改后的数据发送回另一个URL以告诉数据库进行更新。您可能会将数据序列化回JSON并使用另一个'URLSession'来发布它,但是您发送它的具体位置以及格式化方式取决于您要修改的数据库,其Web API以及您的访问级别。 – Robert