既然您已经解析了 JSON,我将创建一个对象类来使用 Core Data 存储数据。一开始有很多关于核心数据使用的内容,但是如果您打算继续进行 iOS 开发,那么值得花时间学习。 Core Data Tuts
我也不知道你打算用你的应用做什么,或者目的,根据你的目的,Core Data 可能有点矫枉过正,但你总是可以每次保存更新的 JSON,覆盖设备的文档目录,然后读回数据并再次解析。
您可以使用以下方法将 JSON 数据写入输出流:
JSONSerialization.writeJSONObject(_ obj: Any, to stream: OutputStream, options opt: JSONSerialization.WritingOptions = [], error: NSErrorPointer)
//Write JSON data into a stream. The stream should be opened and configured.
//The return value is the number of bytes written to the stream, or 0 on error.
//All other behavior of this method is the same as the dataWithJSONObject:options:error: method.
更新:好的,我想我现在看到了您的问题。有两种方法可以将数据返回到视图控制器: 1. 委托模式 2. 闭包。我个人喜欢使用代表而不是闭包。
对于委托,您需要创建一个协议:
protocol SessionDataTaskComplete {
func dataDownloaded(parsedJson : [String : Double])
}
在您的 URLSession 类中,您将需要一个类变量来保存该协议委托:
var dataTaskCompleteDelegate : SessionDataTaskComplete?
然后您需要让您的视图控制器实现该协议:
class MyViewController: UIViewController, SessionDataTaskComplete {
override func viewDidLoad() {
super.viewDidLoad()
//Also assign your viewController as your URLSession's SessionDataTaskComplete delegate
myURLSession.dataTaskCompleteDelegate = self
}
func dataDownloaded(parsedJson : [String : Double]) {
//Handle data as you wish here
}
}
现在在您的 fetchRates() 中,您可以使用该委托将数据传回您的 viewController:
func fetchRates(){
//Set EndPoint URL
let url = URL(string: endPoint)
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print(error as Any)
}
do {
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
let dictonary = json as? [String: Any?]
let ratesJson = dictonary?["rates"] as? [String: Double]
//print(ratesJson as Any)
if (dataTaskCompleteDelegate != nil) {
dataTaskCompleteDelegate!.dataDownloaded(parsedJson: ratesJson)
}
} catch let jsonError {
print(jsonError)
}
}.resume()
}
如果您不习惯使用委托模式,我建议您花时间学习其他方法,因为它在 iOS SDK 中被广泛使用。尝试将它们视为将职责/任务分配给另一个对象的对象。