no message
parent
0c71fbad5f
commit
69d1e4bb0b
@ -0,0 +1,9 @@
|
||||
package com.cloud.diplomaticquarterapp
|
||||
|
||||
class API {
|
||||
companion object{
|
||||
private val BASE = "https://uat.hmgwebservices.com"
|
||||
private val SERVICE = "Services/Patients.svc/REST"
|
||||
val WIFI_CREDENTIALS = "$BASE/$SERVICE/Hmg_SMS_Get_By_ProjectID_And_PatientID"
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,91 @@
|
||||
package com.cloud.diplomaticquarterapp
|
||||
|
||||
import android.content.Intent
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import android.os.Bundle
|
||||
import com.cloud.diplomaticquarterapp.utils.PlatformBridge
|
||||
import io.flutter.embedding.android.FlutterView
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.embedding.engine.dart.DartExecutor
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import io.flutter.view.FlutterMain
|
||||
import java.util.ArrayList
|
||||
|
||||
class FlutterMainActivity : AppCompatActivity() {
|
||||
|
||||
private lateinit var channel: MethodChannel
|
||||
|
||||
private var flutterView: FlutterView? = null
|
||||
companion object {
|
||||
private var flutterEngine: FlutterEngine? = null
|
||||
private const val CHANNEL = "HMG-Platform-Bridge"
|
||||
private const val METHOD_CONNECT_WIFI = "connectHMGGuestWifi"
|
||||
private const val METHOD_SHOW_LOADING = "loading"
|
||||
}
|
||||
|
||||
|
||||
// to get and check returned intent
|
||||
private fun getArgsFromIntent(intent: Intent): Array<String>? {
|
||||
// Before adding more entries to this list, consider that arbitrary
|
||||
// Android applications can generate intents with extra data and that
|
||||
// there are many security-sensitive args in the binary.
|
||||
val args = ArrayList<String>()
|
||||
if (intent.getBooleanExtra("trace-startup", false)) {
|
||||
args.add("--trace-startup")
|
||||
}
|
||||
if (intent.getBooleanExtra("start-paused", false)) {
|
||||
args.add("--start-paused")
|
||||
}
|
||||
if (intent.getBooleanExtra("enable-dart-profiling", false)) {
|
||||
args.add("--enable-dart-profiling")
|
||||
}
|
||||
if (!args.isEmpty()) {
|
||||
return args.toTypedArray()
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
|
||||
val args = getArgsFromIntent(intent)
|
||||
|
||||
// check if flutterEngine is null
|
||||
if (flutterEngine == null) {
|
||||
println(args)
|
||||
flutterEngine = FlutterEngine(this, args)
|
||||
flutterEngine!!.dartExecutor.executeDartEntrypoint(
|
||||
// set which of dart methode will be used here
|
||||
DartExecutor.DartEntrypoint(FlutterMain.findAppBundlePath(), "main")
|
||||
)
|
||||
}
|
||||
|
||||
setContentView(R.layout.activity_flutter_main)
|
||||
|
||||
flutterView = findViewById(R.id.flutterView)
|
||||
flutterView!!.attachToFlutterEngine(flutterEngine!!)
|
||||
|
||||
PlatformBridge(flutterEngine!!.dartExecutor.binaryMessenger, this).create()
|
||||
}
|
||||
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
flutterEngine!!.lifecycleChannel.appIsResumed()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
flutterEngine!!.lifecycleChannel.appIsInactive()
|
||||
}
|
||||
|
||||
override fun onStop() {
|
||||
super.onStop()
|
||||
flutterEngine!!.lifecycleChannel.appIsPaused()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
flutterView!!.detachFromFlutterEngine()
|
||||
super.onDestroy()
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,316 @@
|
||||
package com.cloud.diplomaticquarterapp.utils
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Context
|
||||
import android.net.ConnectivityManager
|
||||
import android.net.wifi.ScanResult
|
||||
import android.net.wifi.WifiConfiguration
|
||||
import android.net.wifi.WifiManager
|
||||
import android.util.Log
|
||||
import com.cloud.diplomaticquarterapp.API
|
||||
import com.cloud.diplomaticquarterapp.FlutterMainActivity
|
||||
import com.github.kittinunf.fuel.core.extensions.jsonBody
|
||||
import com.github.kittinunf.fuel.httpGet
|
||||
import com.github.kittinunf.fuel.httpPost
|
||||
import org.json.JSONObject
|
||||
import java.util.*
|
||||
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
class HMG_Wifi(flutterMainActivity: FlutterMainActivity) {
|
||||
val TAG = "WIFI"
|
||||
|
||||
var context = flutterMainActivity;
|
||||
var completionListener: ((status:Boolean, message:String) -> Unit)? = null
|
||||
|
||||
|
||||
private var SSID = "HMG-GUEST"
|
||||
private var USER_NAME = ""
|
||||
private var PASSWORD = ""
|
||||
private lateinit var PATIENT_ID:String
|
||||
/*
|
||||
* Helpful:
|
||||
* http://stackoverflow.com/questions/5452940/how-can-i-get-android-wifi-scan-results-into-a-list
|
||||
*/
|
||||
fun triggerWifiScan(context: Context) {
|
||||
val wifi = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
wifi.startScan()
|
||||
}
|
||||
|
||||
/*
|
||||
* Helpful:
|
||||
* http://stackoverflow.com/questions/8818290/how-to-connect-to-a-specific-wifi-network-in-android-programmatically
|
||||
*/
|
||||
fun connectToWifiNetworkWith(patientId:String): HMG_Wifi {
|
||||
PATIENT_ID = patientId
|
||||
|
||||
val security = "OPEN"
|
||||
val networkPass = ""
|
||||
Log.d(TAG, "Connecting to SSID \"$SSID\" with password \"$networkPass\" and with security \"$security\" ...")
|
||||
|
||||
// You need to create WifiConfiguration instance like this:
|
||||
val conf = WifiConfiguration()
|
||||
conf.SSID = "\"" + SSID + "\""
|
||||
|
||||
if (security == "OPEN") {
|
||||
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
|
||||
} else if (security == "WEP") {
|
||||
conf.wepKeys[0] = "\"" + networkPass + "\""
|
||||
conf.wepTxKeyIndex = 0
|
||||
conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
|
||||
conf.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40)
|
||||
} else {
|
||||
conf.preSharedKey = "\"" + networkPass + "\""
|
||||
}
|
||||
|
||||
// Then, you need to add it to Android wifi manager settings:
|
||||
val wifiManager = context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
|
||||
val networkId = wifiManager.addNetwork(conf)
|
||||
Log.d(TAG, "Network ID: $networkId")
|
||||
|
||||
//wifiManager.disconnect();
|
||||
val result = wifiManager.enableNetwork(networkId, true)
|
||||
//wifiManager.reconnect();
|
||||
wifiManager.saveConfiguration()
|
||||
|
||||
if(result == true){
|
||||
authNetworkConnection(networkId);
|
||||
}else{
|
||||
completionListener?.let { it(false, "Error connecting to HMG network") }
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
private var authTimer:Timer? = null
|
||||
fun authNetworkConnection(networkId:Int){
|
||||
authTimer = Timer()
|
||||
authTimer?.scheduleAtFixedRate( object : TimerTask(){
|
||||
override fun run() {
|
||||
if (connectedNetworkId() == networkId && connectedNetworkIPAddress() > 0){
|
||||
authServerCall()
|
||||
authTimer?.cancel()
|
||||
}
|
||||
}
|
||||
|
||||
},2000,1000)
|
||||
|
||||
// If wifi not connected in 5 sec terminate with fail status
|
||||
Timer().schedule(object : TimerTask(){
|
||||
override fun run() {
|
||||
if (null != authTimer) {
|
||||
authTimer?.cancel()
|
||||
completionListener?.let { it(false, "Error connecting to HMG network") }
|
||||
}
|
||||
}
|
||||
},5000)
|
||||
|
||||
}
|
||||
|
||||
fun authServerCall(){
|
||||
fun forceCallOverWifi(){
|
||||
val connectivityManager = context.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
connectivityManager.networkPreference = ConnectivityManager.TYPE_WIFI
|
||||
}
|
||||
|
||||
fun call(){
|
||||
forceCallOverWifi()
|
||||
val params = listOf("cmd" to "authenticate", "password" to PASSWORD, "user" to USER_NAME)
|
||||
val serverUrl = "https://captiveportal-login.hmg.com/cgi-bin/login"
|
||||
// val serverUrl = "http://192.168.102.223/cgi-bin/login"
|
||||
serverUrl
|
||||
.httpPost(params)
|
||||
.timeout(10000)
|
||||
.response { request, response, result ->
|
||||
Log.v(TAG,response.statusCode.toString())
|
||||
|
||||
haveInternet { have ->
|
||||
if(have){
|
||||
Log.v(TAG,"Connected to internet via $SSID network at HMG")
|
||||
completionListener?.let { it(true, "Successfully connected to the internet") }
|
||||
}else{
|
||||
Log.e(TAG,"failed to connect to internet via $SSID network at HMG")
|
||||
completionListener?.let { it(false, "Authentication failed or you are already using your credentials on another device") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
haveInternet { has ->
|
||||
if (has){
|
||||
getAuthCredentials {
|
||||
call()
|
||||
}
|
||||
}else{
|
||||
completionListener?.let { it(false,"You must have active internet connection to connect with HMG Network") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun haveInternet(completion:((status:Boolean)->Unit)){
|
||||
"https://captive.apple.com".httpGet().response {request, response, result ->
|
||||
val have = response.statusCode == 200 && String(response.data).contains("<TITLE>Success</TITLE>",true)
|
||||
completion(have)
|
||||
}
|
||||
}
|
||||
|
||||
fun getAuthCredentials(completion:(() -> Unit)){
|
||||
val test = true
|
||||
if (test){
|
||||
USER_NAME = "2300"
|
||||
PASSWORD = "1820"
|
||||
completion()
|
||||
return
|
||||
}
|
||||
|
||||
val jsonBody = """{"PatientID":$PATIENT_ID}"""
|
||||
API.WIFI_CREDENTIALS
|
||||
.httpPost()
|
||||
.jsonBody(jsonBody,Charsets.UTF_8)
|
||||
.response { request, response, result ->
|
||||
val jsonString = String(response.data)
|
||||
Log.d(TAG, "JSON $jsonString")
|
||||
|
||||
if (response.statusCode == 200){
|
||||
|
||||
val jsonObject = JSONObject(jsonString)
|
||||
if(!jsonObject.getString("ErrorMessage").equals("null")){
|
||||
val errorMsg = jsonObject.getString("ErrorMessage")
|
||||
completionListener?.let { it(false,errorMsg) }
|
||||
|
||||
}else{
|
||||
jsonObject.getJSONArray("Hmg_SMS_Get_By_ProjectID_And_PatientIDList").let { array ->
|
||||
array.getJSONObject(0).let { object_ ->
|
||||
if (object_.has("UserName") && object_.has("UserName")){
|
||||
USER_NAME = object_.getString("UserName")
|
||||
PASSWORD = object_.getString("Password")
|
||||
completion()
|
||||
}else{
|
||||
completionListener?.let { it(false,"Failed to get your internet credentials") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}else{
|
||||
completionListener?.let { it(false,"Failed to get your internet credentials") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Helpful:
|
||||
* http://stackoverflow.com/questions/6517314/android-wifi-connection-programmatically
|
||||
*/
|
||||
fun getScanResultSecurity(result: ScanResult): String? {
|
||||
val capabilities: String = result.capabilities
|
||||
val securityModes = arrayOf("WEP", "PSK", "EAP")
|
||||
for (securityMode in securityModes) {
|
||||
if (capabilities.contains(securityMode)) {
|
||||
return securityMode
|
||||
}
|
||||
}
|
||||
return "OPEN"
|
||||
}
|
||||
|
||||
//connects to the given ssid
|
||||
fun connectToWPAWiFi(ssid: String, password: String){
|
||||
|
||||
// WifiUtils.withContext(context)
|
||||
// .connectWith(ssid, "")
|
||||
// .setTimeout(40000)
|
||||
// .onConnectionResult(object : ConnectionSuccessListener {
|
||||
// override fun success() {
|
||||
// Log.v(TAG,"Success")
|
||||
// }
|
||||
//
|
||||
// override fun failed(@NonNull errorCode: ConnectionErrorCode) {
|
||||
// Log.v(TAG,"Failed")
|
||||
// }
|
||||
// })
|
||||
// .start()
|
||||
// if(isConnectedTo(ssid)){ //see if we are already connected to the given ssid
|
||||
// return
|
||||
// }
|
||||
//
|
||||
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
|
||||
// Log.e(TAG, "connection wifi Q")
|
||||
//
|
||||
// val wifiNetworkSpecifier: WifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
|
||||
// .setSsid(ssid)
|
||||
// .setWpa2Passphrase(password)
|
||||
// .build()
|
||||
//
|
||||
// val networkRequest: NetworkRequest = NetworkRequest.Builder()
|
||||
// .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
|
||||
// .setNetworkSpecifier(wifiNetworkSpecifier)
|
||||
// .build()
|
||||
//
|
||||
// var connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
|
||||
// var networkCallback = object : ConnectivityManager.NetworkCallback() {
|
||||
// override fun onAvailable(network: Network) {
|
||||
// super.onAvailable(network)
|
||||
// connectivityManager.bindProcessToNetwork(network)
|
||||
// Log.e(TAG, "onAvailable")
|
||||
// }
|
||||
//
|
||||
// override fun onLosing(network: Network, maxMsToLive: Int) {
|
||||
// super.onLosing(network, maxMsToLive)
|
||||
// Log.e(TAG, "onLosing")
|
||||
// }
|
||||
//
|
||||
// override fun onLost(network: Network) {
|
||||
// super.onLost(network)
|
||||
// Log.e(TAG, "onLosing")
|
||||
// Log.e(TAG, "losing active connection")
|
||||
// }
|
||||
//
|
||||
// override fun onUnavailable() {
|
||||
// super.onUnavailable()
|
||||
// Log.e(TAG, "onUnavailable")
|
||||
// }
|
||||
// }
|
||||
// connectivityManager.requestNetwork(networkRequest, networkCallback)
|
||||
//
|
||||
// }else{
|
||||
//
|
||||
// try {
|
||||
// val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
//
|
||||
// Log.e(TAG, "connection wifi pre Q")
|
||||
//
|
||||
// var netId: Int = wm.addNetwork(getWifiConfig(ssid))
|
||||
// if (netId == -1) netId = getExistingNetworkId(ssid);
|
||||
// wm.saveConfiguration()
|
||||
// if(wm.enableNetwork(netId, true)){
|
||||
// Log.v(TAG,"HMG-GUEST Connected")
|
||||
// }else{
|
||||
// Log.v(TAG,"HMG-GUEST failed to connect")
|
||||
// }
|
||||
// } catch (e: Exception) {
|
||||
// e.printStackTrace()
|
||||
// Log.v(TAG,"HMG-GUEST failed to connect")
|
||||
// }
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
fun connectedNetworkId():Int{
|
||||
val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
return wm.connectionInfo.networkId
|
||||
}
|
||||
|
||||
fun connectedNetworkIPAddress():Int{
|
||||
val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
return wm.connectionInfo.ipAddress
|
||||
}
|
||||
|
||||
fun isConnectedTo(bssid: String):Boolean{
|
||||
val wm:WifiManager= context.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
if(wm.connectionInfo.bssid == bssid){
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,49 @@
|
||||
package com.cloud.diplomaticquarterapp.utils
|
||||
|
||||
import android.os.AsyncTask
|
||||
import android.os.Parcel
|
||||
import android.os.Parcelable
|
||||
import android.util.Log
|
||||
import java.io.BufferedReader
|
||||
import java.io.InputStreamReader
|
||||
import java.io.OutputStreamWriter
|
||||
import java.net.HttpURLConnection
|
||||
import java.net.URL
|
||||
import java.net.URLEncoder
|
||||
|
||||
class HTTPRequest {
|
||||
val TAG = "HTTPRequest"
|
||||
|
||||
fun post(serverURL:String, params:Map<String,String>){
|
||||
|
||||
var encodedParamsList = params.map {
|
||||
URLEncoder.encode(it.key, "UTF-8") + "=" + URLEncoder.encode(it.value,"UTF-8")
|
||||
}
|
||||
|
||||
val postParam = encodedParamsList.joinToString (separator = "&")
|
||||
|
||||
|
||||
val url = URL(serverURL)
|
||||
|
||||
with(url.openConnection() as HttpURLConnection) {
|
||||
requestMethod = "POST"
|
||||
|
||||
val wr = OutputStreamWriter(outputStream)
|
||||
wr.write(postParam)
|
||||
wr.flush()
|
||||
|
||||
BufferedReader(InputStreamReader(inputStream)).use {
|
||||
val response = StringBuffer()
|
||||
|
||||
var inputLIne = it.readLine()
|
||||
while(inputLIne != null) {
|
||||
response.append(inputLIne)
|
||||
inputLIne = it.readLine()
|
||||
}
|
||||
|
||||
it.close()
|
||||
Log.v(TAG,response.toString())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,47 @@
|
||||
package com.cloud.diplomaticquarterapp.utils
|
||||
|
||||
import android.util.Log
|
||||
import com.cloud.diplomaticquarterapp.FlutterMainActivity
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
|
||||
class PlatformBridge(binaryMessenger: BinaryMessenger, flutterMainActivity: FlutterMainActivity) {
|
||||
private var binaryMessenger = binaryMessenger
|
||||
private var mainActivity = flutterMainActivity
|
||||
|
||||
private lateinit var channel: MethodChannel
|
||||
|
||||
companion object {
|
||||
private const val CHANNEL = "HMG-Platform-Bridge"
|
||||
private const val METHOD_CONNECT_WIFI = "connectHMGGuestWifi"
|
||||
private const val METHOD_SHOW_LOADING = "loading"
|
||||
}
|
||||
|
||||
fun create(){
|
||||
channel = MethodChannel(binaryMessenger, CHANNEL)
|
||||
channel.setMethodCallHandler { methodCall: MethodCall, result: MethodChannel.Result ->
|
||||
if (methodCall.method == METHOD_CONNECT_WIFI) {
|
||||
(methodCall.arguments as ArrayList<*>).let {
|
||||
require(it.size > 0 && (it.get(0) is String),lazyMessage = {
|
||||
"Missing or invalid arguments (Must have one argument 'String at 0'"
|
||||
})
|
||||
|
||||
val patientId = it.get(0).toString()
|
||||
HMG_Wifi(mainActivity)
|
||||
.connectToWifiNetworkWith(patientId)
|
||||
.completionListener = { status, message ->
|
||||
|
||||
Log.v(this.javaClass.simpleName, "$status | $message")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}else if (methodCall.method == METHOD_CONNECT_WIFI) {
|
||||
|
||||
}else {
|
||||
result.notImplemented()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,11 +1,21 @@
|
||||
package com.cloud.diplomaticquarterapp
|
||||
import android.os.Bundle
|
||||
import android.os.PersistableBundle
|
||||
import androidx.annotation.NonNull;
|
||||
import io.flutter.embedding.android.FlutterFragmentActivity
|
||||
import io.flutter.embedding.engine.FlutterEngine
|
||||
import io.flutter.plugins.GeneratedPluginRegistrant
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
|
||||
class MainActivity: FlutterFragmentActivity() {
|
||||
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
|
||||
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
|
||||
GeneratedPluginRegistrant.registerWith(flutterEngine);
|
||||
GeneratedPluginRegistrant.registerWith(flutterEngine);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,22 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context=".FlutterMainActivity">
|
||||
|
||||
<io.flutter.embedding.android.FlutterView
|
||||
android:background="#FFFFFF"
|
||||
android:id="@+id/flutterView"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
<TextView
|
||||
android:text="Zohaib"
|
||||
android:textSize="50dp"
|
||||
android:gravity="center"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"/>
|
||||
|
||||
</RelativeLayout>
|
||||
@ -0,0 +1 @@
|
||||
<resources></resources>
|
||||
@ -1 +1 @@
|
||||
5c29d18b2483146f4513132fbdc2a003
|
||||
c948a9de8d5fb4b791dcd366c30ba789
|
||||
@ -0,0 +1,31 @@
|
||||
//
|
||||
// MainFlutterVC.swift
|
||||
// Runner
|
||||
//
|
||||
// Created by ZiKambrani on 25/03/1442 AH.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
import Flutter
|
||||
|
||||
class MainFlutterVC: FlutterViewController {
|
||||
var root_view:MainViewController?
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
/*
|
||||
// MARK: - Navigation
|
||||
|
||||
// In a storyboard-based application, you will often want to do a little preparation before navigation
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
// Get the new view controller using segue.destination.
|
||||
// Pass the selected object to the new view controller.
|
||||
}
|
||||
*/
|
||||
|
||||
}
|
||||
@ -0,0 +1,96 @@
|
||||
//
|
||||
// MainViewController.swift
|
||||
// Runner
|
||||
//
|
||||
// Created by ZiKambrani on 26/03/1442 AH.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
import NVActivityIndicatorView
|
||||
|
||||
class MainViewController: UIViewController {
|
||||
@IBOutlet weak var lblLoadingText: UILabel!
|
||||
@IBOutlet weak var loading: NVActivityIndicatorView!
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
print(loading)
|
||||
}
|
||||
|
||||
func createBridge(flutterViewController:FlutterViewController){
|
||||
let connectHMGGuestWifi = FlutterMethodChannel(name: "HMG-Platform-Bridge",binaryMessenger: flutterViewController.binaryMessenger)
|
||||
connectHMGGuestWifi.setMethodCallHandler { (methodCall, result) in
|
||||
if methodCall.method == "connectHMGGuestWifi"{
|
||||
self.connectWifi(result: result)
|
||||
}else if methodCall.method == "loading"{
|
||||
self.showLoading(flutterMethodCall: methodCall)
|
||||
}else{
|
||||
|
||||
}
|
||||
print("")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Connect HMG-Guest Wifi and Internet
|
||||
func connectWifi(result: @escaping FlutterResult){
|
||||
showLoading(message: "Connecting...")
|
||||
HMG_GUEST.shared.connect { (status, message) in
|
||||
result(status ? 1 : 0)
|
||||
self.showLoading(false);
|
||||
if status{
|
||||
self.showMessage(title:"Congratulations", message:message)
|
||||
}else{
|
||||
self.showMessage(title:"Ooops,", message:message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Loading/Progress
|
||||
private func showLoading(flutterMethodCall:FlutterMethodCall){
|
||||
if let args = flutterMethodCall.arguments as? [Any],
|
||||
let message = args.first as? String, let show = args.last as? Bool{
|
||||
showLoading(message: message, show)
|
||||
}else{
|
||||
assert(true, "Missing or invalid arguments (Must have two argument 'String at 0' and Boolean at 1)")
|
||||
}
|
||||
}
|
||||
func showLoading(message:String = "Please wait...", _ show:Bool = true){
|
||||
DispatchQueue.main.async {
|
||||
if show{
|
||||
self.lblLoadingText.text = message
|
||||
self.loading.superview?.isHidden = false
|
||||
self.loading.startAnimating()
|
||||
}else{
|
||||
self.lblLoadingText.text = ""
|
||||
self.loading.superview?.isHidden = true
|
||||
self.loading.stopAnimating()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Message Dailog
|
||||
func showMessage(title:String, message:String){
|
||||
DispatchQueue.main.async {
|
||||
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert )
|
||||
alert.addAction(UIAlertAction(title: "OK", style: .destructive, handler: nil))
|
||||
self.present(alert, animated: true) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: - Navigation
|
||||
|
||||
// In a storyboard-based application, you will often want to do a little preparation before navigation
|
||||
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
|
||||
if let flutterVC = segue.destination as? MainFlutterVC{
|
||||
flutterVC.root_view = self
|
||||
createBridge(flutterViewController: flutterVC)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
//
|
||||
// GlobalHelper.swift
|
||||
// Runner
|
||||
//
|
||||
// Created by ZiKambrani on 29/03/1442 AH.
|
||||
//
|
||||
|
||||
import UIKit
|
||||
|
||||
@ -0,0 +1,129 @@
|
||||
//
|
||||
// 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("<TITLE>Success</TITLE>"){
|
||||
completion(true)
|
||||
}else{
|
||||
completion(false)
|
||||
}
|
||||
|
||||
}
|
||||
task.resume()
|
||||
}
|
||||
|
||||
}
|
||||
@ -0,0 +1,29 @@
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
class PlatformBridge {
|
||||
static const platform = const MethodChannel("HMG-Platform-Bridge");
|
||||
|
||||
// Method Names
|
||||
static const wifi_connect_method = "connectHMGGuestWifi";
|
||||
static const show_loading_method = "loading";
|
||||
|
||||
Future<Object> connectHMGGuestWifi(String patientId) {
|
||||
print("Invoking platform method: $wifi_connect_method");
|
||||
try {
|
||||
return platform.invokeMethod(wifi_connect_method, [patientId]);
|
||||
} on PlatformException catch (e) {
|
||||
print(e);
|
||||
return Future.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
void showLoading(String message, bool show) async {
|
||||
print("Invoking platform method: $show_loading_method");
|
||||
try {
|
||||
final int result =
|
||||
await platform.invokeMethod(show_loading_method, [message, show]);
|
||||
} on PlatformException catch (e) {
|
||||
print(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue