【发布时间】:2016-04-03 01:23:14
【问题描述】:
我正在使用 Swift 和 Parse 构建应用程序。在几个不同的View Controllers 中,我使用 Parse 来保存和查看对象。但是,如果我必须有 Internet 连接才能访问 Parse。目前,我开发了以下方法来检查互联网:
let url = NSURL(string: "http://myeighthours.com/")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
print(data)
print(response)
print(error)
if let _ = data {
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.activityIndicator.stopAnimating()
//Success
} else {
UIApplication.sharedApplication().endIgnoringInteractionEvents()
self.activityIndicator.stopAnimating()
//Failed
}
}
task.resume()
现在这是一个单独的View Controller。如果我要持续检查互联网,每次尝试访问 Parse 时,我都必须在所有视图控制器中使用此代码。这将是非常乏味和低效的。另外,我必须 1. 为单独的“无 Internet 连接”视图控制器创建一个 segue,或 2.为每个视图控制器添加一个按钮,显示“没有 Internet 连接。点击重试”。如果我关闭我的互联网连接并运行该应用程序,它只是停留在那里加载。我在调试日志中收到此错误消息:
2015-12-29 12:43:19.700 MYAPPNAME[975:354550] [Error]: The Internet connection appears to be offline. (Code: 100, Version: 1.7.5)
2015-12-29 12:43:19.700 MYAPPNAME[975:354550] [Error]: Network connection failed. Making attempt 2 after sleeping for 1.958450 seconds.
2015-12-29 12:43:21.854 MYAPPNAME[975:354549] [Error]: The Internet connection appears to be offline. (Code: 100, Version: 1.7.5)
2015-12-29 12:43:21.855 MYAPPNAME[975:354549] [Error]: Network connection failed. Making attempt 3 after sleeping for 3.916899 seconds.
2015-12-29 12:43:26.132 MYAPPNAME[975:354549] [Error]: The Internet connection appears to be offline. (Code: 100, Version: 1.7.5)
2015-12-29 12:43:26.133 MYAPPNAME[975:354549] [Error]: Network connection failed. Making attempt 4 after sleeping for 7.833799 seconds.
重复检查互联网连接的最有效方法是什么?感谢您的帮助。
【问题讨论】:
-
使用 NStimer 方法反复检查网络连接,也可以全局定义该方法
-
使用github.com/ashleymills/Reachability.swift提供的Reachability.swift
标签: ios xcode swift parse-platform internet-connection