diff --git a/ios/Flutter/.last_build_id b/ios/Flutter/.last_build_id index 0e335bcd..3aa2cd1e 100644 --- a/ios/Flutter/.last_build_id +++ b/ios/Flutter/.last_build_id @@ -1 +1 @@ -4592a16118bc51c556d89309892cf794 \ No newline at end of file +3f3d14a0ae775b56806906c2cb14a1f0 \ No newline at end of file diff --git a/ios/Podfile b/ios/Podfile index d68afba2..5579d926 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -1,5 +1,5 @@ # Uncomment this line to define a global platform for your project -# platform :ios, '11.0' + platform :ios, '11.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index a28140cf..fb2dffc4 100644 --- a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -27,8 +27,6 @@ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES"> - - - - + + - - Bool { - GMSServices.provideAPIKey("AIzaSyCiiJiHkocPbcziHt9O8rGWavDrxHRQys8") - GeneratedPluginRegistrant.register(with: self) - return super.application(application, didFinishLaunchingWithOptions: launchOptions) - } + override func application( _ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + GMSServices.provideAPIKey("AIzaSyCiiJiHkocPbcziHt9O8rGWavDrxHRQys8") + GeneratedPluginRegistrant.register(with: self) + + if let _ = launchOptions?[.location] { + HMG_Geofence().wakeup() + } + + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } } diff --git a/ios/Runner/Controllers/MainFlutterVC.swift b/ios/Runner/Controllers/MainFlutterVC.swift index 22aa5e55..9470e472 100644 --- a/ios/Runner/Controllers/MainFlutterVC.swift +++ b/ios/Runner/Controllers/MainFlutterVC.swift @@ -28,8 +28,8 @@ class MainFlutterVC: FlutterViewController { }else if methodCall.method == "isHMGNetworkAvailable"{ self.isHMGNetworkAvailable(methodCall:methodCall, result: result) - }else{ - + }else if methodCall.method == "registerHmgGeofences"{ + self.registerHmgGeofences(result: result) } print("") @@ -89,18 +89,6 @@ class MainFlutterVC: FlutterViewController { } } } - - // [NEHotspotHelper registerWithOptions:nil queue:queue handler: ^(NEHotspotHelperCommand * cmd) { - // if(cmd.commandType == kNEHotspotHelperCommandTypeFilterScanList) { - // for (NEHotspotNetwork* network in cmd.networkList) { - // NSLog(@"network.SSID = %@",network.SSID); - // } - // } - // }]; - - - - return false } @@ -117,16 +105,16 @@ class MainFlutterVC: FlutterViewController { } } - - - /* - // 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. - } - */ + // Register Geofence + func registerHmgGeofences(result: @escaping FlutterResult){ + flutterMethodChannel?.invokeMethod("getGeofencePreferenceKey", arguments: nil){ geoFencesJsonString in + if let jsonString = geoFencesJsonString as? String{ + let allZones = GeoZoneModel.list(from: jsonString) + HMG_Geofence().register(geoZones: allZones) + + }else{ + } + } + } } diff --git a/ios/Runner/Helper/GeoZoneModel.swift b/ios/Runner/Helper/GeoZoneModel.swift new file mode 100644 index 00000000..d4c6c9e3 --- /dev/null +++ b/ios/Runner/Helper/GeoZoneModel.swift @@ -0,0 +1,47 @@ +// +// GeoZoneModel.swift +// Runner +// +// Created by ZiKambrani on 13/12/2020. +// + +import UIKit + +class GeoZoneModel{ + var geofenceId:Int = -1 + var description:String = "" + var descriptionN:String? + var latitude:String? + var longitude:String? + var radius:Int? + var type:Int? + var projectID:Int? + var imageURL:String? + var isCity:String? + + func identifier() -> String{ + return "\(geofenceId)_\(description)" + } + + class func from(json:[String:Any]) -> GeoZoneModel{ + let model = GeoZoneModel() + model.geofenceId = json["GEOF_ID"] as? Int ?? 0 + model.radius = json["Radius"] as? Int + model.projectID = json["ProjectID"] as? Int + model.type = json["Type"] as? Int + model.description = json["Description"] as? String ?? "" + model.descriptionN = json["DescriptionN"] as? String + model.latitude = json["Latitude"] as? String + model.longitude = json["Longitude"] as? String + model.imageURL = json["ImageURL"] as? String + model.isCity = json["IsCity"] as? String + + return model + } + + class func list(from jsonString:String) -> [GeoZoneModel]{ + let value = dictionaryArray(from: jsonString) + let geoZones = value.map { GeoZoneModel.from(json: $0) } + return geoZones + } +} diff --git a/ios/Runner/Helper/GlobalHelper.swift b/ios/Runner/Helper/GlobalHelper.swift index 3506e26d..1c5b3916 100644 --- a/ios/Runner/Helper/GlobalHelper.swift +++ b/ios/Runner/Helper/GlobalHelper.swift @@ -7,3 +7,47 @@ import UIKit +func dictionaryArray(from:String) -> [[String:Any]]{ + if let data = from.data(using: .utf8) { + do { + return try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] ?? [] + } catch { + print(error.localizedDescription) + } + } + return [] + +} + + +func httpPostRequest(urlString:String, jsonBody:[String:Any], completion:((Bool,[String:Any]?)->Void)?){ + let json: [String: Any] = jsonBody + let jsonData = try? JSONSerialization.data(withJSONObject: json) + + // create post request + let url = URL(string: urlString)! + var request = URLRequest(url: url) + request.httpMethod = "POST" + request.httpBody = jsonData + + let task = URLSession.shared.dataTask(with: request) { data, response, error in + guard let data = data, error == nil else { + print(error?.localizedDescription ?? "No data") + return + } + + let responseJSON = try? JSONSerialization.jsonObject(with: data, options: []) + if let responseJSON = responseJSON as? [String: Any], let status = responseJSON["MessageStatus"] as? Int{ + print(responseJSON) + if status == 1{ + completion?(true,responseJSON) + }else{ + completion?(false,responseJSON) + } + + } + } + + task.resume() + +} diff --git a/ios/Runner/Helper/HMG_Geofence.swift b/ios/Runner/Helper/HMG_Geofence.swift new file mode 100644 index 00000000..20c05333 --- /dev/null +++ b/ios/Runner/Helper/HMG_Geofence.swift @@ -0,0 +1,155 @@ +// +// HMG_Geofence.swift +// Runner +// +// Created by ZiKambrani on 13/12/2020. +// + +import UIKit +import CoreLocation + +fileprivate var df = DateFormatter() +fileprivate var transition = "" + +enum Transition:Int { + case entry = 1 + case exit = 2 +} + +class HMG_Geofence:NSObject{ + var geoZones:[GeoZoneModel]? + var locationManager = CLLocationManager() + + func initLocationManager(){ + locationManager.delegate = self + locationManager.allowsBackgroundLocationUpdates = true + locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters + locationManager.activityType = .other + locationManager.requestAlwaysAuthorization() + } + + func register(geoZones:[GeoZoneModel]){ + self.geoZones = geoZones + + self.geoZones?.forEach({ (zone) in + startMonitoring(zone: zone) + }) + + + } + + func wakeup(){ + initLocationManager() + } + + func monitoredRegions() -> Set{ + return locationManager.monitoredRegions + } +} + + + +// CLLocationManager Delegates +extension HMG_Geofence : CLLocationManagerDelegate{ + + func startMonitoring(zone: GeoZoneModel) { + if !CLLocationManager.isMonitoringAvailable(for: CLCircularRegion.self) { + return + } + + if CLLocationManager.authorizationStatus() != .authorizedAlways { + let message = """ + Your geotification is saved but will only be activated once you grant + HMG permission to access the device location. + """ + debugPrint(message) + } + + if let fenceRegion = region(with: zone){ + locationManager.startMonitoring(for: fenceRegion) + locationManager.requestState(for: fenceRegion) + } + } + + func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { + if region is CLCircularRegion { + handleEvent(for: region,transition: .entry, location: manager.location) + } + } + + func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { + if region is CLCircularRegion { + handleEvent(for: region,transition: .exit, location: manager.location) + } + } + + +} + +// Helpers +extension HMG_Geofence{ + + func handleEvent(for region: CLRegion!, transition:Transition, location:CLLocation?) { + if let zone = geoZone(by: region.identifier){ + notifyUser(forZone: zone, transiotion: transition, location: locationManager.location) + notifyServer(forZone: zone, transiotion: transition, location: locationManager.location) + } + } + + func region(with geoZone: GeoZoneModel) -> CLCircularRegion? { + + if !geoZone.identifier().isEmpty, + let radius = geoZone.radius, let lat = geoZone.latitude, let long = geoZone.longitude, + let radius_d = Double("\(radius)"), let lat_d = Double(lat), let long_d = Double(long){ + + let coordinate = CLLocationCoordinate2D(latitude: lat_d, longitude: long_d) + let region = CLCircularRegion(center: coordinate, radius: radius_d, identifier: geoZone.identifier()) + + region.notifyOnEntry = true + region.notifyOnExit = true + return region + + } + + return nil + } + + func geoZone(by id: String) -> GeoZoneModel? { + return geoZones?.first(where: { $0.identifier() == id}) + } + + + func notifyUser(forZone:GeoZoneModel, transiotion:Transition, location:CLLocation?){ + + } + + func notifyServer(forZone:GeoZoneModel, transiotion:Transition, location:CLLocation?){ + flutterMethodChannel?.invokeMethod("getLogGeofenceFullUrl", arguments: nil){ fullUrlString in + if let url = fullUrlString as? String{ + let body:[String : Any?] = [ + "PointsID":forZone.geofenceId, + "GeoType":transiotion.rawValue, + "PatientID":"1231755", + "ZipCode": "966", + "VersionID": 5.6, + "Channel": 3, + "LanguageID": UserDefaults.standard.string(forKey: "language") ?? "ar", + "IPAdress": "10.20.10.20", + "generalid": "Cs2020@2016$2958", + "PatientOutSA": 0, + "isDentalAllowedBackend": false, + "TokenID": "27v/qqXC/UGS2bgJfRBHYw==", + "DeviceTypeID": 2 + ] + httpPostRequest(urlString: url, jsonBody: body){ (status,json) in + if let json_ = json , status{ + + }else{ + } + } + } + } + } + +} + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index e27d2e38..fbf54435 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -2,6 +2,10 @@ + NSCalendarsUsageDescription + We need access to record you event in to calender. + NSLocationAlwaysUsageDescription + This app will use your location to show cool stuffs near you. CFBundleDevelopmentRegion $(DEVELOPMENT_LANGUAGE) CFBundleExecutable diff --git a/lib/core/model/geofencing/requests/GeoZonesRequestModel.dart b/lib/core/model/geofencing/requests/GeoZonesRequestModel.dart index b807691e..e63a0fb2 100644 --- a/lib/core/model/geofencing/requests/GeoZonesRequestModel.dart +++ b/lib/core/model/geofencing/requests/GeoZonesRequestModel.dart @@ -4,6 +4,7 @@ class GeoZonesRequestModel { GeoZonesRequestModel({this.PatientID}); Map toFlatMap() { + if() return {"PatientID": PatientID.toString()}; } } diff --git a/lib/core/service/geofencing/GeofencingServices.dart b/lib/core/service/geofencing/GeofencingServices.dart index 96e37239..1b39c778 100644 --- a/lib/core/service/geofencing/GeofencingServices.dart +++ b/lib/core/service/geofencing/GeofencingServices.dart @@ -2,11 +2,14 @@ import 'dart:convert'; import 'dart:developer'; import 'package:diplomaticquarterapp/config/config.dart'; +import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/core/model/geofencing/requests/GeoZonesRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/geofencing/requests/LogGeoZoneRequestModel.dart'; import 'package:diplomaticquarterapp/core/model/geofencing/responses/GeoZonesResponseModel.dart'; import 'package:diplomaticquarterapp/core/model/geofencing/responses/LogGeoZoneResponseModel.dart'; import 'package:diplomaticquarterapp/core/service/base_service.dart'; +import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; +import 'package:flutter/cupertino.dart'; import '../../../locator.dart'; @@ -16,9 +19,14 @@ class GeofencingServices extends BaseService { Future> getAllGeoZones(GeoZonesRequestModel request) async { hasError = false; await baseAppClient.post(GET_GEO_ZONES, onSuccess: (dynamic response, int statusCode) { - response['GeoF_PointsList'].forEach((json) { + var zones = response['GeoF_PointsList']; + zones.forEach((json) { geoZones.add(GeoZonesResponseModel().fromJson(json)); }); + + var zonesJsonString = json.encode(zones); + AppSharedPreferences().setString(HMG_GEOFENCES, zonesJsonString); + debugPrint("GEO ZONES saved to AppPreferences with key '$HMG_GEOFENCES'"); }, onFailure: (String error, int statusCode) { hasError = true; return Future.error(error); diff --git a/lib/pages/landing/landing_page.dart b/lib/pages/landing/landing_page.dart index 60d6c187..799ca86e 100644 --- a/lib/pages/landing/landing_page.dart +++ b/lib/pages/landing/landing_page.dart @@ -143,16 +143,18 @@ class _LandingPageState extends State with WidgetsBindingObserver { _firebaseMessaging.requestNotificationPermissions(); } - // Flip Permission Checks [Zohaib Kambrani] - requestPermissions().then((results){ - if(results[Permission.locationAlways].isGranted - || results[Permission.location].isGranted ) - HMG_Geofencing(context) - .loadZones() - .then((instance) => instance.init()); - - if(results[Permission.notification].isGranted) + requestPermissions().then((results) { + if (results[Permission.locationAlways].isGranted || results[Permission.location].isGranted) { + debugPrint("Fetching GEO ZONES from HMG service..."); + locator().getAllGeoZones(GeoZonesRequestModel()).then((geoZones) { + debugPrint("GEO ZONES saved to AppPreferences with key '$HMG_GEOFENCES'"); + debugPrint("Finished Fetching GEO ZONES from HMG service..."); + projectViewModel.platformBridge().registerHmgGeofences(); + }); + } + + if (results[Permission.notification].isGranted) _firebaseMessaging.getToken().then((String token) { sharedPref.setString(PUSH_TOKEN, token); if (token != null && DEVICE_TOKEN == "") { @@ -161,11 +163,11 @@ class _LandingPageState extends State with WidgetsBindingObserver { } }); - if(results[Permission.storage].isGranted); - if(results[Permission.camera].isGranted); - if(results[Permission.photos].isGranted); - if(results[Permission.accessMediaLocation].isGranted); - if(results[Permission.calendar].isGranted); + if (results[Permission.storage].isGranted) ; + if (results[Permission.camera].isGranted) ; + if (results[Permission.photos].isGranted) ; + if (results[Permission.accessMediaLocation].isGranted) ; + if (results[Permission.calendar].isGranted) ; }); // @@ -303,17 +305,15 @@ class _LandingPageState extends State with WidgetsBindingObserver { Permission.accessMediaLocation, Permission.calendar, ].request(); - + var permissionsGranted = await deviceCalendarPlugin.hasPermissions(); if (permissionsGranted.isSuccess && !permissionsGranted.data) { permissionsGranted = await deviceCalendarPlugin.requestPermissions(); - if (!permissionsGranted.isSuccess || !permissionsGranted.data) { - } + if (!permissionsGranted.isSuccess || !permissionsGranted.data) {} } return permissionResults; } - @override Widget build(BuildContext context) { projectViewModel = Provider.of(context); diff --git a/lib/uitl/HMG_Geofence.dart b/lib/uitl/HMG_Geofence.dart index 95ca7c37..54c789ba 100644 --- a/lib/uitl/HMG_Geofence.dart +++ b/lib/uitl/HMG_Geofence.dart @@ -1,189 +1,189 @@ -import 'dart:convert'; -import 'dart:core'; -import 'dart:io'; -import 'dart:isolate'; -import 'dart:math'; -import 'dart:ui'; - -import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; -import 'package:diplomaticquarterapp/core/model/geofencing/requests/GeoZonesRequestModel.dart'; -import 'package:diplomaticquarterapp/core/model/geofencing/requests/LogGeoZoneRequestModel.dart'; -import 'package:diplomaticquarterapp/core/model/geofencing/responses/GeoZonesResponseModel.dart'; -import 'package:diplomaticquarterapp/core/service/geofencing/GeofencingServices.dart'; -import 'package:diplomaticquarterapp/locator.dart'; -import 'package:diplomaticquarterapp/uitl/LocalNotification.dart'; -import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; -import 'package:flutter/cupertino.dart'; -import 'package:flutter/foundation.dart'; -import 'package:geofencing/geofencing.dart'; - -class HMG_Geofencing { - var _testTrigger = false; - static var _isolatePortName = "hmg_geofencing_send_port"; - - List _zones; - List registeredGeofences = []; - - final AndroidGeofencingSettings androidSettings = AndroidGeofencingSettings(initialTrigger: [GeofenceEvent.enter, GeofenceEvent.exit, GeofenceEvent.dwell], loiteringDelay: 1000 * 60); - - final BuildContext context; - final List triggers = List(); - - HMG_Geofencing(this.context) { - triggers.add(GeofenceEvent.enter); - triggers.add(GeofenceEvent.exit); - // triggers.add(GeofenceEvent.dwell); - } - - Future loadZones() async{ - _zones = await locator().getAllGeoZones(GeoZonesRequestModel()); - return this; - } - - void init() async { - // debug check (Testing Geo Zones) - if (kDebugMode) { - addTestingGeofences(); - } - _saveZones(); - await GeofencingManager.initialize(); - await Future.delayed(Duration(seconds: 2)); - _registerIsolatePort(); - _registerGeofences().then((value) { - debugPrint(value.toString()); - if(_testTrigger) { - var events = [GeofenceEvent.enter,GeofenceEvent.exit]; - events.shuffle(); - transitionTrigger(value, null, events.first); - } - }); - - } - - void _saveZones() { - var list = List(); - _zones.forEach((element) { - list.add(element.toJson()); - }); - - var jsonString = jsonEncode(list); - AppSharedPreferences pref = AppSharedPreferences(); - pref.setString(HMG_GEOFENCES, jsonString); - } - - Future> _registerGeofences() async { - registeredGeofences = await GeofencingManager.getRegisteredGeofenceIds(); - - var maxLimit = Platform.isIOS ? 20 : 100; - - if (registeredGeofences.length < maxLimit) { - var notRegistered = _zones.where((element) => !(registeredGeofences.contains(element.geofenceId()))).toList(); - for (int i = 0; i < notRegistered.length; i++) { - var zone = notRegistered.elementAt(i); - var lat = double.tryParse(zone.latitude); - var lon = double.tryParse(zone.longitude); - var rad = double.tryParse(zone.radius.toString()); - - if (lat != null || lon != null || rad != null) { - await GeofencingManager.registerGeofence(GeofenceRegion(zone.geofenceId(), lat, lon, rad, triggers), transitionTrigger); - registeredGeofences.add(zone.geofenceId()); - if (registeredGeofences.length >= maxLimit) { - break; - } - await Future.delayed(Duration(milliseconds: 100)); - debugPrint("Geofence: ${zone.description} registered"); - } else { - debugPrint("Geofence: ${zone.description} registered"); - } - } - } - return registeredGeofences; - } - - void addTestingGeofences() { - _zones.add(GeoZonesResponseModel.get("24.777577,46.652675", 150, "msH")); - _zones.add(GeoZonesResponseModel.get("24.691136,46.650116", 150, "zkH")); - _zones.add(GeoZonesResponseModel.get("24.7087913,46.6656461", 150, "csO")); - } - - static void transitionTrigger(List id, Location location, GeofenceEvent event) { - var dataToSend = id.map((element) => {"event": event, "geofence_id": element}).toList() ?? []; - final SendPort send = IsolateNameServer.lookupPortByName(_isolatePortName); - send?.send(dataToSend); - } - - ReceivePort _port = ReceivePort(); - void _registerIsolatePort() async{ - IsolateNameServer.registerPortWithName(_port.sendPort, _isolatePortName); - _port.listen((dynamic data) { - - Future result = AppSharedPreferences().getStringWithDefaultValue(HMG_GEOFENCES,"[]"); - result.then((jsonString){ - - List jsonList = json.decode(jsonString) ?? []; - List geoList = jsonList.map((e) => GeoZonesResponseModel().fromJson(e)).toList() ?? []; - - (data as List).forEach((element) async { - GeofenceEvent geofenceEvent = element["event"]; - String geofence_id = element["geofence_id"]; - - GeoZonesResponseModel geoZone = _findByGeofenceFrom(geoList, by: geofence_id); - if(geoZone != null) { - LocalNotification.getInstance().showNow( - title: "GeofenceEvent: ${_nameOf(geofenceEvent)}", - subtitle: geoZone.description, - payload: json.encode(geoZone.toJson())); - - _logGeoZoneToServer(zoneId: geoZone.geofId, transition: _idOf(geofenceEvent)); - } - - await Future.delayed(Duration(milliseconds: 700)); - - }); - - }); - }); - } - - _logGeoZoneToServer({int zoneId, int transition}){ - locator() - .logGeoZone(LogGeoZoneRequestModel(GeoType: transition, PointsID: zoneId ?? 1)) - .then((response){ - - }).catchError((error){ - - }); - - } - - GeoZonesResponseModel _findByGeofenceFrom(List list, { String by}) { - var have = list.where((element) => element.geofenceId() == by).toList().first; - return have; - } - - String _nameOf(GeofenceEvent event) { - switch (event) { - case GeofenceEvent.enter: - return "Enter"; - case GeofenceEvent.exit: - return "Exit"; - case GeofenceEvent.dwell: - return "dWell"; - default: - return event.toString(); - } - } - - int _idOf(GeofenceEvent event){ - switch (event) { - case GeofenceEvent.enter: - return 1; - case GeofenceEvent.exit: - return 2; - case GeofenceEvent.dwell: - return 3; - default: - return -1; - } - } -} +// import 'dart:convert'; +// import 'dart:core'; +// import 'dart:io'; +// import 'dart:isolate'; +// import 'dart:math'; +// import 'dart:ui'; +// +// import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; +// import 'package:diplomaticquarterapp/core/model/geofencing/requests/GeoZonesRequestModel.dart'; +// import 'package:diplomaticquarterapp/core/model/geofencing/requests/LogGeoZoneRequestModel.dart'; +// import 'package:diplomaticquarterapp/core/model/geofencing/responses/GeoZonesResponseModel.dart'; +// import 'package:diplomaticquarterapp/core/service/geofencing/GeofencingServices.dart'; +// import 'package:diplomaticquarterapp/locator.dart'; +// import 'package:diplomaticquarterapp/uitl/LocalNotification.dart'; +// import 'package:diplomaticquarterapp/uitl/app_shared_preferences.dart'; +// import 'package:flutter/cupertino.dart'; +// import 'package:flutter/foundation.dart'; +// import 'package:geofencing/geofencing.dart'; +// +// class HMG_Geofencing { +// var _testTrigger = false; +// static var _isolatePortName = "hmg_geofencing_send_port"; +// +// List _zones; +// List registeredGeofences = []; +// +// final AndroidGeofencingSettings androidSettings = AndroidGeofencingSettings(initialTrigger: [GeofenceEvent.enter, GeofenceEvent.exit, GeofenceEvent.dwell], loiteringDelay: 1000 * 60); +// +// final BuildContext context; +// final List triggers = List(); +// +// HMG_Geofencing(this.context) { +// triggers.add(GeofenceEvent.enter); +// triggers.add(GeofenceEvent.exit); +// // triggers.add(GeofenceEvent.dwell); +// } +// +// Future loadZones() async{ +// _zones = await locator().getAllGeoZones(GeoZonesRequestModel()); +// return this; +// } +// +// void init() async { +// // debug check (Testing Geo Zones) +// if (kDebugMode) { +// addTestingGeofences(); +// } +// _saveZones(); +// await GeofencingManager.initialize(); +// await Future.delayed(Duration(seconds: 2)); +// _registerIsolatePort(); +// _registerGeofences().then((value) { +// debugPrint(value.toString()); +// if(_testTrigger) { +// var events = [GeofenceEvent.enter,GeofenceEvent.exit]; +// events.shuffle(); +// transitionTrigger(value, null, events.first); +// } +// }); +// +// } +// +// void _saveZones() { +// var list = List(); +// _zones.forEach((element) { +// list.add(element.toJson()); +// }); +// +// var jsonString = jsonEncode(list); +// AppSharedPreferences pref = AppSharedPreferences(); +// pref.setString(HMG_GEOFENCES, jsonString); +// } +// +// Future> _registerGeofences() async { +// registeredGeofences = await GeofencingManager.getRegisteredGeofenceIds(); +// +// var maxLimit = Platform.isIOS ? 20 : 100; +// +// if (registeredGeofences.length < maxLimit) { +// var notRegistered = _zones.where((element) => !(registeredGeofences.contains(element.geofenceId()))).toList(); +// for (int i = 0; i < notRegistered.length; i++) { +// var zone = notRegistered.elementAt(i); +// var lat = double.tryParse(zone.latitude); +// var lon = double.tryParse(zone.longitude); +// var rad = double.tryParse(zone.radius.toString()); +// +// if (lat != null || lon != null || rad != null) { +// await GeofencingManager.registerGeofence(GeofenceRegion(zone.geofenceId(), lat, lon, rad, triggers), transitionTrigger); +// registeredGeofences.add(zone.geofenceId()); +// if (registeredGeofences.length >= maxLimit) { +// break; +// } +// await Future.delayed(Duration(milliseconds: 100)); +// debugPrint("Geofence: ${zone.description} registered"); +// } else { +// debugPrint("Geofence: ${zone.description} registered"); +// } +// } +// } +// return registeredGeofences; +// } +// +// void addTestingGeofences() { +// _zones.add(GeoZonesResponseModel.get("24.777577,46.652675", 150, "msH")); +// _zones.add(GeoZonesResponseModel.get("24.691136,46.650116", 150, "zkH")); +// _zones.add(GeoZonesResponseModel.get("24.7087913,46.6656461", 150, "csO")); +// } +// +// static void transitionTrigger(List id, Location location, GeofenceEvent event) { +// var dataToSend = id.map((element) => {"event": event, "geofence_id": element}).toList() ?? []; +// final SendPort send = IsolateNameServer.lookupPortByName(_isolatePortName); +// send?.send(dataToSend); +// } +// +// ReceivePort _port = ReceivePort(); +// void _registerIsolatePort() async{ +// IsolateNameServer.registerPortWithName(_port.sendPort, _isolatePortName); +// _port.listen((dynamic data) { +// +// Future result = AppSharedPreferences().getStringWithDefaultValue(HMG_GEOFENCES,"[]"); +// result.then((jsonString){ +// +// List jsonList = json.decode(jsonString) ?? []; +// List geoList = jsonList.map((e) => GeoZonesResponseModel().fromJson(e)).toList() ?? []; +// +// (data as List).forEach((element) async { +// GeofenceEvent geofenceEvent = element["event"]; +// String geofence_id = element["geofence_id"]; +// +// GeoZonesResponseModel geoZone = _findByGeofenceFrom(geoList, by: geofence_id); +// if(geoZone != null) { +// LocalNotification.getInstance().showNow( +// title: "GeofenceEvent: ${_nameOf(geofenceEvent)}", +// subtitle: geoZone.description, +// payload: json.encode(geoZone.toJson())); +// +// _logGeoZoneToServer(zoneId: geoZone.geofId, transition: _idOf(geofenceEvent)); +// } +// +// await Future.delayed(Duration(milliseconds: 700)); +// +// }); +// +// }); +// }); +// } +// +// _logGeoZoneToServer({int zoneId, int transition}){ +// locator() +// .logGeoZone(LogGeoZoneRequestModel(GeoType: transition, PointsID: zoneId ?? 1)) +// .then((response){ +// +// }).catchError((error){ +// +// }); +// +// } +// +// GeoZonesResponseModel _findByGeofenceFrom(List list, { String by}) { +// var have = list.where((element) => element.geofenceId() == by).toList().first; +// return have; +// } +// +// String _nameOf(GeofenceEvent event) { +// switch (event) { +// case GeofenceEvent.enter: +// return "Enter"; +// case GeofenceEvent.exit: +// return "Exit"; +// case GeofenceEvent.dwell: +// return "dWell"; +// default: +// return event.toString(); +// } +// } +// +// int _idOf(GeofenceEvent event){ +// switch (event) { +// case GeofenceEvent.enter: +// return 1; +// case GeofenceEvent.exit: +// return 2; +// case GeofenceEvent.dwell: +// return 3; +// default: +// return -1; +// } +// } +// } diff --git a/lib/uitl/PlatformBridge.dart b/lib/uitl/PlatformBridge.dart index b4769475..65e924c5 100644 --- a/lib/uitl/PlatformBridge.dart +++ b/lib/uitl/PlatformBridge.dart @@ -1,5 +1,6 @@ import 'dart:developer'; +import 'package:diplomaticquarterapp/config/config.dart'; import 'package:diplomaticquarterapp/config/localized_values.dart'; import 'package:diplomaticquarterapp/config/shared_pref_kay.dart'; import 'package:diplomaticquarterapp/core/service/client/base_app_client.dart'; @@ -34,7 +35,13 @@ class PlatformBridge { switch (methodCall.method) { case 'localizedValue': String key = methodCall.arguments.toString(); - return platformLocalizedText(key); + return localizedValue(key); + + case 'getGeofencePreferenceKey': + return getGeofencePreferenceKey(); + + case 'getLogGeofenceFullUrl': + return getLogGeofenceFullUrl(); case 'test': return 123.0; @@ -49,12 +56,22 @@ class PlatformBridge { //--------------------------------- // Incoming below //--------------------------------- - static Future platformLocalizedText(String forKey) async { + static Future localizedValue(String forKey) async { String currentLanguage = await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar'); Object localized = platformLocalizedValues[forKey][currentLanguage]; return (localized != null || (localized is String)) ? localized : forKey; } + static Future getGeofencePreferenceKey() async { + var res = await sharedPref.getStringWithDefaultValue(HMG_GEOFENCES, "[]"); + return res; + } + + static Future getLogGeofenceFullUrl() async { + var res = BASE_URL + LOG_GEO_ZONES; + return res; + } + //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// //--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--//--// @@ -67,6 +84,7 @@ class PlatformBridge { static const is_hmg_network_available_method = "isHMGNetworkAvailable"; static const enable_wifi_if_not = "enableWifiIfNot"; static const show_loading_method = "loading"; + static const register_Hmg_Geofences = "registerHmgGeofences"; Future connectHMGInternetWifi(String patientId) { print("Invoking platform method: $hmg_internet_wifi_connect_method"); @@ -116,4 +134,9 @@ class PlatformBridge { print(e); } } + + // GEO Fences + void registerHmgGeofences() async { + final int result = await platform.invokeMethod(register_Hmg_Geofences); + } } diff --git a/pubspec.yaml b/pubspec.yaml index a4129776..4a9206e0 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -162,7 +162,6 @@ dependencies: # Dep by Zohaib shimmer: ^1.1.2 - geofencing: ^0.1.0 dev_dependencies: flutter_test: