如何检查Swift中的网络状态?在Objective-C Reachability.h .m文件可用.现在怎么办?如何查看我是在线还是离线?
Ash*_*lls 14
如果您正在寻找Swift实现Apple的Reachability类,您可以看一下:
http://github.com/ashleymills/Reachability.swift
这是一个使用通知和闭包的课程.
Con*_*nor 11
你仍然可以在Swift中使用Reachability.洛根对如何Objective-C的文件添加到桥接报一个很好的答案在这里.设置桥接标头后,可以从Swift代码中调用Reachability方法.像这样的东西会起作用:
class func hasConnectivity() -> Bool {
let reachability: Reachability = Reachability.reachabilityForInternetConnection()
let networkStatus: Int = reachability.currentReachabilityStatus().value
return networkStatus != 0
}
Run Code Online (Sandbox Code Playgroud)
我会给出最好的解决方案,希望它有所帮助.
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork()->Bool{
var Status:Bool = false
let url = NSURL(string: "http://google.com/")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "HEAD"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
var response: NSURLResponse?
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
Status = true
}
}
else
{
let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
alert.show()
}
return Status
}
}
Run Code Online (Sandbox Code Playgroud)
如何访问或调用其他类:
if Reachability.isConnectedToNetwork() == true {
// write your code
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
27205 次 |
最近记录: |