I'm new to iOS development, and am writing a VPN app, using the OpenVPN framework. I'm making use of the Network Extension target to tunnel network traffic to our OpenVPN server. However, when trying to debug, I can't attach the debugger to the Network Extension - it's stuck at "Waiting to Attach" in the Debug Navigator view.
In this blog post by Alex Grebenyuk he gives some recommendations for troubleshooting when you fail to attach the debugger to the extension. I've meticulously checked all of them, and my app correctly uses everything there: Both the app and the network extension have the Packet Tunnel Network Extension capability and bundle names all work out.
Some more info on the bundle names in case it might be relevant:
Bundle name for the app: com.example.Example-App
Bundle name for the Network Extension: com.example.Example-App.Example-VPN
Group name: group.com.example.Example-App
I'm out of ideas here. Could the problem be in the Network Extension never being started? It doesn't seem to be the case, because the startTunnel() function is called. The code for starting the VPN through the extension:
func configureVPN(serverAddress: String) {
guard let configData = readTestFile() else { return }
// Test file with ovpn configuration seems is read in correctly - contents are shown if printed to console.
self.providerManager?.loadFromPreferences { error in
if error == nil {
let tunnelProtocol = NETunnelProviderProtocol()
tunnelProtocol.serverAddress = serverAddress
tunnelProtocol.providerBundleIdentifier = "com.example.Example-App.Example-VPN" // bundle id of the network extension target
tunnelProtocol.providerConfiguration = ["ovpn": configData]
self.providerManager.protocolConfiguration = tunnelProtocol
self.providerManager.localizedDescription = "Example VPN"
self.providerManager.isEnabled = true
self.providerManager.saveToPreferences(completionHandler: { (error) in
if error == nil {
self.providerManager.loadFromPreferences(completionHandler: { (error) in
do {
print("Trying to start connection now") // This line is printed to the Console
try self.providerManager.connection.startVPNTunnel() // start the VPN tunnel.
} catch let error {
print(error.localizedDescription)
}
})
}
})
}
}
}
Not sure if this is relevant information, but I am using the OpenVPNAdapter in the PacketTunnelProvider, following this tutorial:
import NetworkExtension
import OpenVPNAdapter
class PacketTunnelProvider: NEPacketTunnelProvider {
lazy var vpnAdapter: OpenVPNAdapter = {
let adapter = OpenVPNAdapter()
adapter.delegate = self
return adapter
}()
let vpnReachability = OpenVPNReachability()
var startHandler: ((Error?) -> Void)?
var stopHandler: (() -> Void)?
override func startTunnel(
options: [String : NSObject]?,
completionHandler: #escaping (Error?) -> Void
) {
// There are many ways to provide OpenVPN settings to the tunnel provider. For instance,
// you can use `options` argument of `startTunnel(options:completionHandler:)` method or get
// settings from `protocolConfiguration.providerConfiguration` property of `NEPacketTunnelProvider`
// class. Also you may provide just content of a ovpn file or use key:value pairs
// that may be provided exclusively or in addition to file content.
// In our case we need providerConfiguration dictionary to retrieve content
// of the OpenVPN configuration file. Other options related to the tunnel
// provider also can be stored there.
guard
let protocolConfiguration = protocolConfiguration as? NETunnelProviderProtocol,
let providerConfiguration = protocolConfiguration.providerConfiguration
else {
fatalError()
}
guard let ovpnFileContent: Data = providerConfiguration["ovpn"] as? Data else {
fatalError()
}
let configuration = OpenVPNConfiguration()
configuration.fileContent = ovpnFileContent
configuration.settings = [ :
// Additional parameters as key:value pairs may be provided here
]
// Uncomment this line if you want to keep TUN interface active during pauses or reconnections
// configuration.tunPersist = true
// Apply OpenVPN configuration
let evaluation: OpenVPNConfigurationEvaluation
do {
evaluation = try vpnAdapter.apply(configuration: configuration)
} catch {
completionHandler(error)
return
}
// Provide credentials if needed
if !evaluation.autologin {
// If your VPN configuration requires user credentials you can provide them by
// `protocolConfiguration.username` and `protocolConfiguration.passwordReference`
// properties. It is recommended to use persistent keychain reference to a keychain
// item containing the password.
guard let username: String = protocolConfiguration.username else {
fatalError()
}
// Retrieve a password from the keychain
let password: String = "Test"
let credentials = OpenVPNCredentials()
credentials.username = username
credentials.password = password
do {
try vpnAdapter.provide(credentials: credentials)
} catch {
completionHandler(error)
return
}
}
// Checking reachability. In some cases after switching from cellular to
// WiFi the adapter still uses cellular data. Changing reachability forces
// reconnection so the adapter will use actual connection.
vpnReachability.startTracking { [weak self] status in
guard status == .reachableViaWiFi else { return }
self?.vpnAdapter.reconnect(afterTimeInterval: 5)
}
// Establish connection and wait for .connected event
startHandler = completionHandler
vpnAdapter.connect(using: packetFlow as! OpenVPNAdapterPacketFlow)
}
override func stopTunnel(
with reason: NEProviderStopReason,
completionHandler: #escaping () -> Void
) {
stopHandler = completionHandler
if vpnReachability.isTracking {
vpnReachability.stopTracking()
}
vpnAdapter.disconnect()
}
}
extension PacketTunnelProvider: OpenVPNAdapterDelegate {
// OpenVPNAdapter calls this delegate method to configure a VPN tunnel.
// `completionHandler` callback requires an object conforming to `OpenVPNAdapterPacketFlow`
// protocol if the tunnel is configured without errors. Otherwise send nil.
// `OpenVPNAdapterPacketFlow` method signatures are similar to `NEPacketTunnelFlow` so
// you can just extend that class to adopt `OpenVPNAdapterPacketFlow` protocol and
// send `self.packetFlow` to `completionHandler` callback.
func openVPNAdapter(
_ openVPNAdapter: OpenVPNAdapter,
configureTunnelWithNetworkSettings networkSettings: NEPacketTunnelNetworkSettings?,
completionHandler: #escaping (Error?) -> Void
) {
// In order to direct all DNS queries first to the VPN DNS servers before the primary DNS servers
// send empty string to NEDNSSettings.matchDomains
networkSettings?.dnsSettings?.matchDomains = [""]
// Set the network settings for the current tunneling session.
setTunnelNetworkSettings(networkSettings, completionHandler: completionHandler)
}
// Process events returned by the OpenVPN library
func openVPNAdapter(
_ openVPNAdapter: OpenVPNAdapter,
handleEvent event:
OpenVPNAdapterEvent, message: String?
) {
switch event {
case .connected:
if reasserting {
reasserting = false
}
guard let startHandler = startHandler else { return }
startHandler(nil)
self.startHandler = nil
case .disconnected:
guard let stopHandler = stopHandler else { return }
if vpnReachability.isTracking {
vpnReachability.stopTracking()
}
stopHandler()
self.stopHandler = nil
case .reconnecting:
reasserting = true
default:
break
}
}
// Handle errors thrown by the OpenVPN library
func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleError error: Error) {
// Handle only fatal errors
guard let fatal = (error as NSError).userInfo[OpenVPNAdapterErrorFatalKey] as? Bool,
fatal == true else { return }
if vpnReachability.isTracking {
vpnReachability.stopTracking()
}
if let startHandler = startHandler {
startHandler(error)
self.startHandler = nil
} else {
cancelTunnelWithError(error)
}
}
}
Any help with this would be hugely appreciated! Thanks.
You need to attache the bundle name and not the bundle identifier and the bundle name should not be an identifier. The PRODUCT_BUNDLE_IDENTIFIER of your network extension would be something like com.example.my-network-extension-id (it cannot be com.example.Example-App.Example-VPN, as a third period is not allowed for network extension IDs) and the PRODUCT_NAME would be something like My Network Extension, and you would then attach to My Network Extension (yes, with spaces and no extension).
Related
We have an android app that has a custom VPN built into it. We have used VpnService class to implement this feature. This is the code in Android used to build a virtual interface.
We create the tunnel first and then create multiple udp sessions in multiple threads.
try {
if (vpnInterface == null) {
Builder builder = new Builder();
builder.setMtu(1024);
builder.addAddress("10.10.10.9", 32);
builder.addRoute("10.10.10.0", 24);
vpnInterface = builder
.setSession(getString(R.string.app_name))
.setConfigureIntent(pendingIntent)
.setBlocking(true)
.establish();
FileDescriptor vpnFileDescriptor = vpnInterface.getFileDescriptor();
writePacket(vpnFileDescriptor);
readPacket(vpnFileDescriptor);
}
} catch (Exception e) {
e.printStackTrace();
}
We want to do the exact same thing is ios as well. I'm a swift newbie and I tried to work with Network extensions and use the NEPacketTunnelNetworkSettings to replicate this feature but I could not make it work. How would I create a layer 3 virtual network interface in iOS? This is what I have so far.
import NetworkExtension
class PacketTunnelProvider: NEPacketTunnelProvider {
override func startTunnel(options: [String : NSObject]?, completionHandler: #escaping (Error?) -> Void) {
let serverAddress = "10.10.10.10"
let clientAddress = "10.10.10.9"
let mtu = 1024 as NSNumber?
let netMask = "255.255.255.255"
let settings = NEPacketTunnelNetworkSettings(tunnelRemoteAddress: serverAddress)
settings.ipv4Settings = NEIPv4Settings(addresses: [clientAddress], subnetMasks: [netMask])
settings.ipv4Settings?.includedRoutes = [NEIPv4Route.default()]
settings.ipv4Settings?.excludedRoutes = []
settings.mtu = mtu
setTunnelNetworkSettings(settings){ error in
if let e = error {
print("ERROR:",e)
NSLog("Settings error %#", e.localizedDescription)
} else {
NSLog("Settings %#", "Settings have been created successfully and tunnel has started")
}
}
}
override func stopTunnel(with reason: NEProviderStopReason, completionHandler: #escaping () -> Void) {
// Add code here to start the process of stopping the tunnel.
completionHandler()
}
override func handleAppMessage(_ messageData: Data, completionHandler: ((Data?) -> Void)?) {
// Add code here to handle the message.
if let handler = completionHandler {
handler(messageData)
}
}
override func sleep(completionHandler: #escaping () -> Void) {
// Add code here to get ready to sleep.
completionHandler()
}
override func wake() {
// Add code here to wake up.
}
}
I've created a MacOS app project which contains System Network Extension (DNS proxy). With help of https://developer.apple.com/forums/thread/81103?answerId=246229022 and How to use NEDNSProxyProvider in iOS 11. I enabled DNSProxyProvider. When I built the app for the first time a prompt asked to allow the system extension. I allowed it and Under network in system preference, I can see DNS is not running (yellow dot).
Not running
I added OSSystemextensionRequest from the container App. This is my code.
import Cocoa
import NetworkExtension
import SystemExtensions
import OSLog
class ViewController: NSViewController {
let log=OSLog(subsystem:"com.example.applesamplecode.DNSTestBed", category: "app")
let manager = NEDNSProxyManager.shared()
private func installSystemExtension() {
os_log("DNSFProxy: installing system extension")
let request = OSSystemExtensionRequest.activationRequest(
forExtensionWithIdentifier: "my system extension's bundle indentifier",
queue: .main
)
request.delegate = self
OSSystemExtensionManager.shared.submitRequest(request)
}
private func enable() {
NSLog("enabled already ",self.manager.isEnabled )
NSLog(self.manager.isEnabled ? "Yes" : "No")
self.update {
self.manager.localizedDescription = "DNS"
let proto = NEDNSProxyProviderProtocol()
proto.serverAddress = "localhost"
proto.providerBundleIdentifier = "my system extension's bundle indentifier"
self.manager.providerProtocol = proto
self.manager.isEnabled = true
}
NSLog(self.manager.isEnabled ? "Yes" : "No")
}
private func disable() {
self.update {
self.manager.isEnabled = false
}
}
private func update(_ body: #escaping () -> Void) {
self.manager.loadFromPreferences { (error) in
guard error == nil else {
NSLog("DNS Test App: load error")
return
}
body()
self.manager.saveToPreferences { (error) in
guard error == nil else {
NSLog("DNS Test App: save error")
return
}
NSLog("DNS Test App: saved")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.enable()
self.installSystemExtension()
}
}
extension ViewController: OSSystemExtensionRequestDelegate {
func request(_ request: OSSystemExtensionRequest, actionForReplacingExtension existing: OSSystemExtensionProperties, withExtension ext: OSSystemExtensionProperties) -> OSSystemExtensionRequest.ReplacementAction {
os_log("DNSProxy: Replacing extension %# version %# with version %#", request.identifier, existing.bundleShortVersion, ext.bundleShortVersion)
return .replace
}
func requestNeedsUserApproval(_ request: OSSystemExtensionRequest) {
os_log("DNSProxy: Extension %# requires user approval", request.identifier)
}
func request(_ request: OSSystemExtensionRequest, didFailWithError error: Error) {
os_log("DNSProxy: System extension request failed: %#", error.localizedDescription)
}
/* Other delegate methods here */
func request(_ request: OSSystemExtensionRequest, didFinishWithResult result: OSSystemExtensionRequest.Result) {
switch result {
case .completed:
var manager = NEDNSProxyManager.shared()
case .willCompleteAfterReboot:
os_log("DNSProxy: willCompleteAfterReboot")
#unknown default:
os_log("DNSProxy: default")
}
}
}
Info.plist of system extension:
info.plist
I'm getting an error when the activation request happens: The operation couldn’t be completed. (OSSystemExtensionErrorDomain error 1.). Any help would be great. Thanks.
P.S: I also posted this in apple forums https://developer.apple.com/forums/thread/717647
I'm using a companion app to authorize a user with a 3rd party service. Once authorized, I update a UserDefaults variable to true. On the companion app side, the view updates correctly and shows that the user has been authenticated. However, on the watch OS side the view does not update. Would I need to use the Watch Connectivity API and send a message to the watch to update the state? Or is there a simple way?
Phone App
struct AuthenticationView: View {
#State private var startingWebAuthenticationSession = false
#AppStorage("authorized") private var authorized = false
var body: some View {
Group {
if !authorized {
VStack {
Button("Connect", action: { self.startingWebAuthenticationSession = true })
.webAuthenticationSession(isPresented: $startingWebAuthenticationSession) {
WebAuthenticationSession(
url: URL(string: "https://service.com/oauth/authorize?scope=email%2Cread_stats&response_type=code&redirect_uri=watch%3A%2F%2Foauth-callback&client_id=\(clientId)")!,
callbackURLScheme: callbackURLScheme
) { callbackURL, error in
guard error == nil, let successURL = callbackURL else {
return
}
let oAuthCode = NSURLComponents(string: (successURL.absoluteString))?.queryItems?.filter({$0.name == "code"}).first
guard let authorizationCode = oAuthCode?.value else { return }
let url = URL(string: "https://service.com/oauth/token")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let params = "client_id=\(clientId)&client_secret=\(clientSecret)&grant_type=authorization_code&code=\(authorizationCode)&redirect_uri=\(callbackURLScheme)://oauth-callback";
request.httpBody = params.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("Error took place \(error)")
return
}
if let data = data, let response = String(data: data, encoding: .utf8) {
let accessTokenResponse: AccessTokenResponse = try! JSONDecoder().decode(AccessTokenResponse.self, from: response.data(using: .utf8)!)
let defaults = UserDefaults.standard
authorized = true
startingWebAuthenticationSession = false
defaults.set(accessTokenResponse.access_token, forKey: DefaultsKeys.accessToken) //TODO: Store securely
ConnectivityService.shared.send(authorized: true)
}
}
task.resume()
}
.prefersEphemeralWebBrowserSession(false)
}
}
}
else {
VStack {
Text("Authenticated!")
}
}
}
}
}
WatchOS
import SwiftUI
struct ConnectView: View {
#ObservedObject var connectivityService: ConnectivityService
var body: some View {
if !$connectivityService.authorized.wrappedValue {
VStack {
Text("Open the app on your primary device to connect.")
}
}
else {
//Some other view
}
}
}
EDIT:
Trying with Watch Connectivity API but the issue I'm experiencing is that when I authenticate from the phone, it'll take some time for the ConnectView to update the authorized variable. I know Watch Connectivity API doesn't update right away but at minimum I'd need some way for the watch to pick up that a secret access token has been retrieved and it can transition to the next view; whether that's through a shared state variable, UserDefaults, or whatever other mechanism.
Here is the ConnectivityService class I'm using:
import Foundation
import Combine
import WatchConnectivity
final class ConnectivityService: NSObject, ObservableObject {
static let shared = ConnectivityService()
#Published var authorized: Bool = false
override private init() {
super.init()
#if !os(watchOS)
guard WCSession.isSupported() else {
return
}
#endif
WCSession.default.delegate = self
WCSession.default.activate()
}
public func send(authorized: Bool, errorHandler: ((Error) -> Void)? = nil) {
guard WCSession.default.activationState == .activated else {
return
}
#if os(watchOS)
guard WCSession.default.isCompanionAppInstalled else {
return
}
#else
guard WCSession.default.isWatchAppInstalled else {
return
}
#endif
let authorizationInfo: [String: Bool] = [
DefaultsKeys.authorized: authorized
]
WCSession.default.sendMessage(authorizationInfo, replyHandler: nil)
WCSession.default.transferUserInfo(authorizationInfo)
}
}
extension ConnectivityService: WCSessionDelegate {
func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { }
func session(
_ session: WCSession,
didReceiveUserInfo userInfo: [String: Any] = [:]
) {
let key = DefaultsKeys.authorized
guard let authorized = userInfo[key] as? Bool else {
return
}
self.authorized = authorized
}
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
self.authorized = true
}
#if os(iOS)
func sessionDidBecomeInactive(_ session: WCSession) {
}
func sessionDidDeactivate(_ session: WCSession) {
WCSession.default.activate()
}
#endif
}
I tried doing these two lines but they have varying results:
WCSession.default.sendMessage(authorizationInfo, replyHandler: nil)
WCSession.default.transferUserInfo(authorizationInfo)
In the first line, XCode will say that no watch app could be found, even though I'm connected to both physical devices through XCode; launch phone first then watch. I believe the first one is immediate and the second is more of when the queue feels like it. Sometimes if I hard close the watch app, it'll pick up the state change in the authorized variable, sometimes it won't. Very frustrating inter-device communication.
UserDefaults doesn't pick up the access token value on the watch side. Maybe I have to use App Groups?
I do see this error on the Watch side:
Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.
So I thought to try and encapsulate the self.authorized = authorized call into something like:
DispatchQueue.main.async {
self.authorized = authorized
}
But it didn't do anything as far as solving the immediate state change issue.
I have just shifted to Alamofire 5.
Earlier I used URLSession and Certificate Pinner and to handle auth challenge I used delegate method of URLSessionDelegate with hash values
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge,
completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("being challanged! for \(challenge.protectionSpace.host)")
guard let trust = challenge.protectionSpace.serverTrust else {
print("invalid trust!")
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
let credential = URLCredential(trust: trust)
let pinner = setupCertificatePinner(host: challenge.protectionSpace.host)
if (!pinner.validateCertificateTrustChain(trust)) {
print("failed: invalid certificate chain!")
challenge.sender?.cancel(challenge)
}
if (pinner.validateTrustPublicKeys(trust)) {
completionHandler(.useCredential, credential)
} else {
didPinningFailed = true
print("couldn't validate trust for \(challenge.protectionSpace.host)")
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
Having moved to Alamofire 5, there is no method sessionDidReceiveChallenge which was available in earlier version.
I tried:
private let session: Session = {
let manager = ServerTrustManager(allHostsMustBeEvaluated: true, evaluators:
["devDomain.com": DisabledTrustEvaluator(),
"prodDomain.com": PublicKeysTrustEvaluator()])
let configuration = URLSessionConfiguration.af.default
return Session(configuration: configuration, serverTrustManager: manager)
}()
But I get error:
Error Domain=Alamofire.AFError Code=11 "Server trust evaluation failed due to reason: No public keys were found or provided for evaluation."
Update:
I'd still prefer a way to parse it using 256 fingerprint only, as we get domains and its hashes in first api call.
First you need a ServerTrustEvaluating that handle the certificate pinning a simple implement would be something similar to
public final class CertificatePinnerTrustEvaluator: ServerTrustEvaluating {
public init() {}
func setupCertificatePinner(host: String) -> CertificatePinner {
//get the CertificatePinner
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
let pinner = setupCertificatePinner(host: host)
if (!pinner.validateCertificateTrustChain(trust)) {
print("failed: invalid certificate chain!")
throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
}
if (!pinner.validateTrustPublicKeys(trust)) {
print ("couldn't validate trust for \(host)")
throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
}
}
}
To be able to use the same evaluator I would suggest to subclass ServerTrustManager to return the same evaluator I did it like this:
class CertificatePinnerServerTrustManager: ServerTrustManager {
let evaluator = CertificatePinnerTrustEvaluator()
init() {
super.init(allHostsMustBeEvaluated: true, evaluators: [:])
}
open override func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? {
return evaluator
}
}
after that you should be ready to go by creating the session and passing the manager to it
private let session: Session = {
let trustManager = CertificatePinnerServerTrustManager()
return Session(serverTrustManager: trustManager)
}()
My reference was the method urlSession(_:task:didReceive:completionHandler:) in Alamofire source in SessionDelegate.swift at line 86 (Alamofire V5.2.1)
If you want to pin with public keys you need to provide the certificates from which to parse those public keys in the bundle of your app, or otherwise provide them to PublicKeysTrustEvaluator.
I was wanting to know if anyone knows how to detect if there is data transfer or not within an iOS app. I am using a Swift Reachability library to detect if there is wifi or cellular connection, but this does not let me know if there is actual data being transferred.
My app starts out with a WKWebView, and in the case there is no data being transferred to load the webview that takes up the entire screen, I would like to present an alertController to the user.
Reachability lets me know if there is a connection to wifi or a cellular network, but they don't help with letting me know if there is any data being transferred. I'm testing with my wifi on, but with no network connection, and I'm unable to present any alertController as connection is always passing true for isReachable().
Does anyone know how to go about this? Thank you.
Alamofire Provide the functionaly to check the network status. So here it is in detail with some other functionality.
I have created an APIClient Manager class in my project.
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 is a constant declared as following
let kNetworkStatusConnectedNotification = "kNetworkStatusConnectedNotification"
Now, Where you want to observe the network changes in your application, register the notification in that viewController as follows
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(HomeViewController.applicationIsConnectedToNetwok), name: kNetworkStatusConnectedNotification, object: nil)
and in the selector do whatever you want to do when you get network connectivity
func applicationIsConnectedToNetwok() {
// e.g LoadData
}
I have written this method in my Session class and I am using it to check connectivity mannualy
func isNetworkReachable() -> Bool {
return YourAPIClient.sharedClient.isNetworkReachable()
}
I have added some comments in the code for your understanding. I hope it helps.