我正在构建一个有几页的iOS应用程序。我在登录时获取完整的App(对于所有页面)JSON数据,然后将它们存储到CoreData中,以便数据立即可供离线查看。 (只读)
我的问题是如何实现在线/离线观看场景。
用户应该能够在线时对Server API执行CRUD操作。此时需要更新CoreData和UI
用户应该只能在离线状态下读取数据。
任何建议都将不胜感激。
答案 0 :(得分:1)
我会使用THIS Git project来执行此操作:
extension UIViewController {
/**
Check network availability with Ashley Mills' Reachability.
*/
func doReachability(_ reachability: Reachability,_ completion: @escaping (_ connected: Bool?) -> Void) {
reachability.whenReachable = { reachability in
completion(true)
}
reachability.whenUnreachable = { _ in
completion(false)
}
do{
try reachability.startNotifier()
}catch{
print("could not start reachability notifier")
}
}
然后在视图中你需要这样做:
let reachability = Reachability()!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
doReachability(reachability) { (connected) in
if connected == false {
print("No Connection! Your device isn't connected to the network." /* DO ANY WORK HERE */
{ else {/*Connected work here*/}
})
}
}