// // HMG_GUEST.swift // HMG-iOS-Wifi // // Created by ZiKambrani on 23/03/1442 AH. // Copyright © 1442 ZiKambrani. All rights reserved. // import UIKit import NetworkExtension import SystemConfiguration.CaptiveNetwork class HMG_GUEST{ static let shared = HMG_GUEST() private let SSID = "HMG-GUEST" private let USER = "1301" private let PASS = "8928" var complete:((_ status:Bool, _ message:String) -> Void)! func connect(completion:@escaping ((_ status:Bool, _ message:String) -> Void)){ complete = completion if isAlreadyConnected() { hasInternet { (has) in if has == true{ self.complete(true, "You already connected to internet") return }else{ self.authenticate() } } }else{ connect() } } private func connect() { let hotspotConfig = NEHotspotConfiguration(ssid: SSID) hotspotConfig.joinOnce = true NEHotspotConfigurationManager.shared.apply(hotspotConfig) {[weak self] (error) in guard let self = self else { return; } if let error = error { self.complete(false, error.localizedDescription ?? "Error connecting to HMG wifi network" ) }else{ _ = Timer.scheduledTimer(withTimeInterval: 2, repeats: false) { (timer) in self.authenticate() } } } } func authenticate(){ func callLogin(){ let parameters = "Login=Log%20In&cmd=authenticate&password=1820&user=2300" let postData = parameters.data(using: .utf8) var request = URLRequest(url: URL(string: "https://captiveportal-login.hmg.com/cgi-bin/login")!,timeoutInterval: 5) request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpMethod = "POST" request.httpBody = postData let task = URLSession.shared.dataTask(with: request) { data, response, error in // guard let data = data else { // self.complete(false, "Error at authentication") // return // } self.hasInternet { (has) in self.complete(has, has ? "Successfully connected to the internet" : "Authentication failed or you are already using your credentials on another device") } } task.resume() } self.hasInternet { (has) in if has == true{ self.complete(true, "Your internet account is already authenticated") }else{ callLogin() } } } private func isAlreadyConnected() -> Bool{ var currentSSID: String? if let interfaces = CNCopySupportedInterfaces() as NSArray? { for interface in interfaces { if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? { currentSSID = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String break } } } print("CurrentConnectedSSID: \(currentSSID)") return currentSSID == SSID } func hasInternet( completion:@escaping ((Bool)->Void)){ let testUrl = "https://captive.apple.com" var request = URLRequest(url: URL(string: testUrl)!,timeoutInterval: 5) request.httpMethod = "GET" let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data else { completion(false) return } let resp = String(data: data, encoding: .utf8)! if resp.contains("