我想知道是否有人知道如何检测iOS应用中是否有数据传输。我正在使用Swift Reachability库来检测是否存在wifi或蜂窝连接,但是如果有实际数据被传输,这不会让我知道。
我的应用程序以WKWebView开头,如果没有数据传输加载占用整个屏幕的webview,我想向用户提供一个alertController。
可达性让我知道是否存在与wifi或蜂窝网络的连接,但如果有任何数据被传输,它们无法让我知道。我正在测试我的wifi,但没有网络连接,我无法呈现任何alertController,因为连接总是为isReachable()传递true。
有谁知道如何解决这个问题?谢谢。
答案 0 :(得分:0)
Alamofire提供功能以检查网络状态。所以这里有一些其他功能。
我在项目中创建了一个APIClient Manager类。
import UIKit
import Alamofire
import AlamofireNetworkActivityIndicator
// Completion handeler
typealias TSAPIClientCompletionBlock = (response: NSHTTPURLResponse?, result: AnyObject?, error: NSError?) -> Void
// MARK: -
class TSAPIClient: Manager {
// MARK: - Properties methods
private let manager = NetworkReachabilityManager(host: "www.apple.com") // could be any website, Just to check connectivity
private var serviceURL: NSURL?
// MARK: - init & deinit methods
init(baseURL: NSURL,
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil) {
super.init(configuration: configuration, delegate: delegate, serverTrustPolicyManager: serverTrustPolicyManager)
var aURL = baseURL
// Ensure terminal slash for baseURL path, so that NSURL relativeToURL works as expected
if aURL.path?.characters.count > 0 && !aURL.absoluteString.hasSuffix("/") {
aURL = baseURL.URLByAppendingPathComponent("")
}
serviceURL = baseURL
NetworkActivityIndicatorManager.sharedManager.isEnabled = true
observeNetworkStatus()
}
// MARK: - Public methods
func serverRequest(methodName: String, parameters: [String : AnyObject]? , isPostRequest: Bool, headers: [String : String]?, completionBlock: TSAPIClientCompletionBlock) -> Request {
let url = NSURL(string: methodName, relativeToURL: serviceURL)
print("\(url)")
let request = self.request(isPostRequest ? .POST : .GET, url!, parameters: parameters, encoding: isPostRequest ? .JSON : .URL, headers: headers)
.validate(statusCode: 200..<600)
.responseJSON { response in
switch response.result {
case .Success:
completionBlock(response: response.response, result: response.result.value, error: nil
)
break
case .Failure(let error):
completionBlock(response: response.response, result: nil, error: error)
break
}
}
return request
}
func cancelAllRequests() {
session.getAllTasksWithCompletionHandler { tasks in
for task in tasks {
task.cancel()
}
}
}
// this will contiously observe network changes
func observeNetworkStatus() {
manager?.listener = { status in
print("Network Status Changed: \(status)")
if status == .NotReachable {
} else if status == .Unknown {
} else {
// status is reachable
// posting a notification for network connectivity NSNotificationCenter.defaultCenter().postNotificationName(kNetworkStatusConnectedNotification, object: nil)
}
}
manager?.startListening()
}
// If you want to check network manually for Example before pushing a viewController.
func isNetworkReachable() -> Bool {
return manager?.isReachable ?? false
}
}
kNetworkStatusConnectedNotification 是一个声明如下的常量
let kNetworkStatusConnectedNotification = "kNetworkStatusConnectedNotification"
现在,如果您想在应用程序中观察网络更改,请在该viewController中注册通知,如下所示
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.applicationIsConnectedToNetwok), name: kNetworkStatusConnectedNotification, object: nil)
并在选择器中执行网络连接时要执行的操作
func applicationIsConnectedToNetwok() {
// e.g LoadData
}
我在Session类中编写了这个方法,我正在使用它来检查mannualy的连接性
func isNetworkReachable() -> Bool {
return YourAPIClient.sharedClient.isNetworkReachable()
}
我在代码中添加了一些注释,供您理解。我希望它有所帮助。