cordova-plugin-mserviceinterface-2.0 1.0.72 → 1.0.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cordova-plugin-mserviceinterface-2.0",
3
- "version": "1.0.72",
3
+ "version": "1.0.74",
4
4
  "description": "This plugin establishes the connection to the native interface and performs the requested task.",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/plugin.xml CHANGED
@@ -2,7 +2,7 @@
2
2
  <plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
3
3
  xmlns:android="http://schemas.android.com/apk/res/android"
4
4
  id="cordova-plugin-mserviceinterface-2.0"
5
- version="1.0.72">
5
+ version="1.0.74">
6
6
  <name>mserviceinterface-2.0</name>
7
7
  <description>This plugin establishes the connection to the native interface and performs the requested task.</description>
8
8
  <author>selfservit@gmail.com</author>
@@ -25,6 +25,12 @@
25
25
  <framework src="com.google.zxing:core:3.3.2" />
26
26
  <framework src="com.journeyapps:zxing-android-embedded:3.6.0@aar" />
27
27
  <framework src="id.zelory:compressor:2.1.1" />
28
+ <edit-config file="AndroidManifest.xml" mode="merge" target="/manifest/application">
29
+ <application android:allowBackup="false" />
30
+ <application android:networkSecurityConfig="@xml/network_security_config" />
31
+ <application android:requestLegacyExternalStorage="true" />
32
+ <application android:fullBackupContent="@xml/my_backup_rules" />
33
+ </edit-config>
28
34
  <config-file target="res/xml/config.xml" parent="/*">
29
35
  <feature name="mInterface" >
30
36
  <param name="android-package" value="com.selfservit.util.mInterface"/>
@@ -42,6 +48,7 @@
42
48
  <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
43
49
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
44
50
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
51
+ <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
45
52
  <uses-permission android:name="android.permission.READ_PHONE_STATE" />
46
53
  <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
47
54
  </config-file>
@@ -55,6 +62,11 @@
55
62
  <action android:name="com.example.checkservice" />
56
63
  </intent-filter>
57
64
  </receiver>
65
+ <receiver android:enabled="true" android:exported="true" android:name="com.selfservit.util.GeofenceBroadcastReceiver">
66
+ <intent-filter>
67
+ <action android:name="com.google.android.gms.location.GeofenceEvent" />
68
+ </intent-filter>
69
+ </receiver>
58
70
  <provider android:name="com.selfservit.util.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true">
59
71
  <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/opener_paths" />
60
72
  </provider>
@@ -67,6 +79,8 @@
67
79
  <source-file src="src/android/CallbackProgressDialog.java" target-dir="src/com/selfservit/util/" />
68
80
  <source-file src="src/android/FileProvider.java" target-dir="src/com/selfservit/util/" />
69
81
  <source-file src="src/android/res/xml/opener_paths.xml" target-dir="res/xml" />
82
+ <source-file src="src/android/res/xml/network_security_config.xml" target-dir="res/xml" />
83
+ <source-file src="src/android/res/xml/my_backup_rules.xml" target-dir="res/xml" />
70
84
  </platform>
71
85
  <platform name="ios">
72
86
  <config-file target="*-Info.plist" parent="NSCameraUsageDescription">
@@ -0,0 +1,116 @@
1
+ package com.selfservit.util;
2
+
3
+ import android.app.NotificationChannel;
4
+ import android.app.NotificationManager;
5
+ import android.app.PendingIntent;
6
+ import android.content.BroadcastReceiver;
7
+ import android.content.Context;
8
+ import android.content.Intent;
9
+ import android.os.Build;
10
+ import android.util.Log;
11
+ import android.widget.Toast;
12
+
13
+ import androidx.core.app.NotificationCompat;
14
+ import androidx.core.app.NotificationManagerCompat;
15
+
16
+ import com.google.android.gms.location.Geofence;
17
+ import com.google.android.gms.location.GeofencingEvent;
18
+ import com.selfservit.pegdev.MainActivity;
19
+ import com.selfservit.pegdev.R;
20
+
21
+ import org.json.JSONObject;
22
+
23
+ import java.io.File;
24
+ import java.io.FileOutputStream;
25
+ import java.io.FileWriter;
26
+ import java.io.IOException;
27
+ import java.io.OutputStreamWriter;
28
+
29
+ public class GeofenceBroadcastReceiver extends BroadcastReceiver {
30
+
31
+ private static final String TAG = "GeofenceReceiver";
32
+ private static final String CHANNEL_ID = "geofence_channel";
33
+
34
+ @Override
35
+ public void onReceive(Context context, Intent intent) {
36
+ GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
37
+
38
+ if (geofencingEvent.hasError()) {
39
+ Log.e(TAG, "GeofencingEvent error: " + geofencingEvent.getErrorCode());
40
+ return;
41
+ }
42
+ String enterMessage = intent.getStringExtra("enterMessage");
43
+ String exitMessage = intent.getStringExtra("exitMessage");
44
+ int geofenceTransition = geofencingEvent.getGeofenceTransition();
45
+ if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
46
+ geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
47
+ String transitionType = geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ? "enter" : "exit";
48
+
49
+ for (Geofence geofence : geofencingEvent.getTriggeringGeofences()) {
50
+ String geofenceId = geofence.getRequestId();
51
+ writeEventToJsonFile(context, geofenceId, transitionType);
52
+ createNotificationChannel(context);
53
+ String message = (transitionType.equals("enter") ? enterMessage : exitMessage);
54
+ sendNotification(context, "GeoFence", message);
55
+ // showToast(context, "Geofence " + transitionType + ": " + geofenceId);
56
+ }
57
+ }
58
+ }
59
+ private void showToast(Context context, String message) {
60
+ //Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_LONG).show();
61
+ }
62
+ private void writeEventToJsonFile(Context context, String geofenceId, String eventType) {
63
+ File notificationsFile, fileDirectory;
64
+ try {
65
+ JSONObject jsonObject = new JSONObject();
66
+ jsonObject.put("eventName", eventType);
67
+ jsonObject.put("geofenceID", geofenceId);
68
+ String[] parameters = geofenceId.split("--");
69
+ fileDirectory = new File(new File(context.getExternalFilesDir(""), "") + "/" + parameters[0] + "/" + parameters[1] + "/" + parameters[2] + "/" + parameters[3] + "/" + "geofence");
70
+ if (!fileDirectory.exists()) {
71
+ boolean success = fileDirectory.mkdirs();
72
+ if (!success) {
73
+ System.out.println("Directory not created");
74
+ }
75
+ };
76
+ notificationsFile = new File(fileDirectory, geofenceId + "--" + eventType + ".json");
77
+ FileWriter fw = new FileWriter(notificationsFile);
78
+ fw.write(mInterfaceUtil.encrypt(jsonObject.toString()));
79
+ fw.close();
80
+ Log.i(TAG, "Event written to file: " + geofenceId + ".json");
81
+ } catch (Exception e) {
82
+ Log.e(TAG, "Error writing event to JSON file", e);
83
+ }
84
+ }
85
+
86
+ private void sendNotification(Context context, String title, String message) {
87
+ Intent intent = new Intent(context, MainActivity.class);
88
+ intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
89
+ PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
90
+ NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, CHANNEL_ID)
91
+ .setSmallIcon(R.drawable.ic_notification)
92
+ .setContentTitle(title)
93
+ .setContentText(message)
94
+ .setAutoCancel(true)
95
+ .setContentIntent(pendingIntent);
96
+ NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
97
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
98
+ NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Channel human readable title", NotificationManager.IMPORTANCE_DEFAULT);
99
+ notificationManager.createNotificationChannel(channel);
100
+ };
101
+ int notificationId = UUID.randomUUID().hashCode();
102
+ notificationManager.notify(notificationId, notificationBuilder.build());
103
+ }
104
+
105
+ private void createNotificationChannel(Context context) {
106
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
107
+ CharSequence name = "Geofence Channel";
108
+ String description = "Channel for geofence events";
109
+ int importance = NotificationManager.IMPORTANCE_HIGH;
110
+ NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
111
+ channel.setDescription(description);
112
+ NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
113
+ notificationManager.createNotificationChannel(channel);
114
+ }
115
+ }
116
+ }
@@ -6,6 +6,7 @@ import android.Manifest;
6
6
  import android.app.Activity;
7
7
  import android.app.ActivityManager;
8
8
  import android.app.AlertDialog;
9
+ import android.app.PendingIntent;
9
10
  import android.app.ProgressDialog;
10
11
  import android.content.ContentResolver;
11
12
  import android.content.ContentUris;
@@ -57,6 +58,9 @@ import com.google.android.gms.common.api.GoogleApiClient;
57
58
  import com.google.android.gms.common.api.PendingResult;
58
59
  import com.google.android.gms.common.api.ResultCallback;
59
60
  import com.google.android.gms.common.api.Status;
61
+ import com.google.android.gms.location.Geofence;
62
+ import com.google.android.gms.location.GeofencingClient;
63
+ import com.google.android.gms.location.GeofencingRequest;
60
64
  import com.google.android.gms.location.LocationRequest;
61
65
  import com.google.android.gms.location.LocationServices;
62
66
  import com.google.android.gms.location.LocationSettingsRequest;
@@ -94,6 +98,7 @@ import java.net.URL;
94
98
  import java.text.SimpleDateFormat;
95
99
  import java.util.ArrayList;
96
100
  import java.util.Arrays;
101
+ import java.util.Collections;
97
102
  import java.util.Date;
98
103
  import java.util.List;
99
104
  import java.util.Stack;
@@ -134,6 +139,8 @@ public class mInterface extends CordovaPlugin implements com.google.android.gms.
134
139
  private static final long FASTEST_INTERVAL = 5 * 60 * 1000;
135
140
  public static String attachmentDestPath = "";
136
141
 
142
+ private GeofencingClient geofencingClient;
143
+ private PendingIntent geofencePendingIntent;
137
144
  /* START SERVICE WHEN USER COMES FROM INACTIVE TO ACTIVE STATE IF SERVICE NOT RUNNING */
138
145
  @Override
139
146
  public void onResume(boolean multitasking) {
@@ -158,7 +165,28 @@ public class mInterface extends CordovaPlugin implements com.google.android.gms.
158
165
  if (mInterfaceUtil.packageName.equals("")) {
159
166
  mInterfaceUtil.packageName = cordova.getActivity().getApplicationContext().getPackageName().split("\\.")[2];
160
167
  }
161
- if (action.equals("AppCleanUp")) {
168
+ if (action.equals("viewRoute")) {
169
+ double endLat = Double.parseDouble(args.getJSONObject(0).optString("destinationLat"));
170
+ double endLng = Double.parseDouble(args.getJSONObject(0).optString("destinationLng"));
171
+ openMaps(endLat, endLng, callbackContext);
172
+ return true;
173
+ } else if (action.equals("addGeoFence")) {
174
+ geofencingClient = LocationServices.getGeofencingClient(cordova.getActivity().getApplicationContext());
175
+ double latitude = Double.parseDouble(args.getJSONObject(0).optString("latitude"));
176
+ double longitude = Double.parseDouble(args.getJSONObject(0).optString("longitude"));
177
+ float radius = Float.parseFloat(args.getJSONObject(0).optString("radius"));
178
+ String geofenceId = args.getJSONObject(0).optString("geofenceId");
179
+ String enterMessage = args.getJSONObject(0).optString("enterNotificationMsg");
180
+ String exitMessage = args.getJSONObject(0).optString("exitNotificationMsg");
181
+
182
+ addGeofence(latitude, longitude, radius, geofenceId, enterMessage, exitMessage, callbackContext, cordova.getActivity().getApplicationContext());
183
+ callbackContext.success("Success");
184
+ return true;
185
+ } else if (action.equals("removeGeofence")) {
186
+ String geofenceId = args.getJSONObject(0).optString("geofenceId");
187
+ removeGeofence(geofenceId, callbackContext);
188
+ return true;
189
+ } else if (action.equals("AppCleanUp")) {
162
190
  mInterfaceUtil.appCleanUp(callbackContext, cordova.getActivity().getApplicationContext());
163
191
  } else if (action.equals("StartService")) {
164
192
  try {
@@ -966,7 +994,6 @@ public class mInterface extends CordovaPlugin implements com.google.android.gms.
966
994
  result = new PluginResult(PluginResult.Status.ERROR, "copyAttachmentFile failed, exception is : " + e.getMessage());
967
995
  callback.sendPluginResult(result);
968
996
  }
969
-
970
997
  } else if (action.equals("getMyAccountsData")) {
971
998
  try {
972
999
  String folderPath = mInterfaceUtil.rootDirectory + "/" + args.getJSONObject(0).optString("folderPath");
@@ -987,7 +1014,56 @@ public class mInterface extends CordovaPlugin implements com.google.android.gms.
987
1014
  }
988
1015
  return true;
989
1016
  }
1017
+ private void addGeofence(double latitude, double longitude, float radius, String geofenceId, String enterMessage, String exitMessage, CallbackContext callbackContext, Context context) {
1018
+ Geofence geofence = new Geofence.Builder()
1019
+ .setRequestId(geofenceId)
1020
+ .setCircularRegion(latitude, longitude, radius)
1021
+ .setExpirationDuration(Geofence.NEVER_EXPIRE)
1022
+ .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
1023
+ .build();
990
1024
 
1025
+ GeofencingRequest geofencingRequest = new GeofencingRequest.Builder()
1026
+ .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
1027
+ .addGeofence(geofence)
1028
+ .build();
1029
+
1030
+ geofencePendingIntent = getGeofencePendingIntent(enterMessage, exitMessage);
1031
+
1032
+ if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
1033
+
1034
+ return;
1035
+ }
1036
+ geofencingClient.addGeofences(geofencingRequest, geofencePendingIntent)
1037
+ .addOnSuccessListener(aVoid -> {
1038
+ callbackContext.success("Geofence added successfully");
1039
+ Log.i(TAG, "Geofence added successfully");
1040
+ })
1041
+ .addOnFailureListener(e -> {
1042
+ callbackContext.error("Failed to add geofence");
1043
+ Log.e(TAG, "Failed to add geofence", e);
1044
+ });
1045
+ }
1046
+ private void removeGeofence(String geofenceId, CallbackContext callbackContext) {
1047
+ geofencingClient.removeGeofences(Collections.singletonList(geofenceId))
1048
+ .addOnSuccessListener(aVoid -> {
1049
+ callbackContext.success("Geofence removed successfully");
1050
+ Log.i(TAG, "Geofence removed successfully");
1051
+ })
1052
+ .addOnFailureListener(e -> {
1053
+ callbackContext.error("Failed to remove geofence");
1054
+ Log.e(TAG, "Failed to remove geofence", e);
1055
+ });
1056
+ }
1057
+ private PendingIntent getGeofencePendingIntent( String enterMessage, String exitMessage) {
1058
+ if (geofencePendingIntent != null) {
1059
+ return geofencePendingIntent;
1060
+ }
1061
+ Intent intent = new Intent(cordova.getActivity(), GeofenceBroadcastReceiver.class);
1062
+ intent.putExtra("enterMessage", enterMessage);
1063
+ intent.putExtra("exitMessage", exitMessage);
1064
+ geofencePendingIntent = PendingIntent.getBroadcast(cordova.getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
1065
+ return geofencePendingIntent;
1066
+ }
991
1067
  public static ArrayList<JSONObject> getJsonDataFromFiles(String folderPath) {
992
1068
  ArrayList<JSONObject> dataArray = new ArrayList<>();
993
1069
  try {
@@ -2472,4 +2548,11 @@ public class mInterface extends CordovaPlugin implements com.google.android.gms.
2472
2548
  }
2473
2549
  return "";
2474
2550
  }
2551
+
2552
+ private void openMaps( double endLat, double endLng, CallbackContext callbackContext) {
2553
+ Uri mapUri = Uri.parse("https://www.google.com/maps?daddr=" + endLat + "," + endLng);
2554
+ Intent mapIntent = new Intent(Intent.ACTION_VIEW, mapUri);
2555
+ this.cordova.getActivity().startActivity(mapIntent);
2556
+ callbackContext.success("Google Maps intent launched successfully");
2557
+ }
2475
2558
  }
@@ -0,0 +1,5 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <full-backup-content>
3
+ <exclude domain="file" path="shared_prefs" />
4
+ <exclude domain="file" path="cache" />
5
+ </full-backup-content>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="utf-8"?>
2
+ <network-security-config>
3
+ <base-config cleartextTrafficPermitted="true">
4
+ <trust-anchors>
5
+ <certificates src="system" />
6
+ </trust-anchors>
7
+ </base-config>
8
+ </network-security-config>
@@ -42,6 +42,7 @@
42
42
  UIInterfaceOrientation _lastOrientation;
43
43
  }
44
44
  @property(strong) NSString* callbackID;
45
+ - (void)viewRoute:(CDVInvokedUrlCommand*)command;
45
46
  - (void)GetFCMUtils:(CDVInvokedUrlCommand *)command;
46
47
  -(void)GetBase64String:(CDVInvokedUrlCommand *)command;
47
48
  - (void)ValidateAppStateInfo;
@@ -109,6 +110,7 @@
109
110
  - (void)GetSyncIndicator:(CDVInvokedUrlCommand*)command;
110
111
  - (void)CopyAttachmentFile:(CDVInvokedUrlCommand*)command;
111
112
  - (void)getMyAccountsData:(CDVInvokedUrlCommand*)command;
113
+ - (void)addGeoFence:(CDVInvokedUrlCommand*)command;
112
114
  @property (strong, nonatomic) CLLocationManager * locationManager;
113
115
  @property (strong, nonatomic) NSMutableArray * coordinatesArray;
114
116
  @property (weak, nonatomic) IBOutlet UIButton *btnGallery;
@@ -29,6 +29,166 @@
29
29
  @synthesize controller = docController;
30
30
  @synthesize callbackID;
31
31
 
32
+ - (void)viewRoute:(CDVInvokedUrlCommand*)command {
33
+ CDVPluginResult* pluginResult = nil;
34
+
35
+ NSDictionary *dict = [[command arguments] objectAtIndex:0];
36
+ NSString* destinationLat = dict[@"destinationLat"];
37
+ NSString* destinationLng = dict[@"destinationLng"];
38
+
39
+ if (destinationLat != nil && destinationLng != nil && [destinationLat length] != 0 && [destinationLng length] != 0) {
40
+ NSString* urlString = [NSString stringWithFormat:@"https://www.google.com/maps?daddr=%@,%@", destinationLat, destinationLng];
41
+ NSURL* url = [NSURL URLWithString:urlString];
42
+
43
+ if ([[UIApplication sharedApplication] canOpenURL:url]) {
44
+ [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
45
+ if (success) {
46
+ CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Google Maps launched successfully"];
47
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
48
+ } else {
49
+ CDVPluginResult *result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Failed to launch Google Maps app"];
50
+ [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
51
+ }
52
+ }];
53
+ } else {
54
+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Google Maps app is not installed"];
55
+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
56
+ }
57
+ } else {
58
+ pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Invalid coordinates"];
59
+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
60
+ }
61
+ }
62
+ - (void)addGeoFence:(CDVInvokedUrlCommand *)command {
63
+ NSDictionary *dict = [[command arguments] objectAtIndex:0];
64
+ @try {
65
+
66
+ if (!self.locationManager) {
67
+ self.locationManager = [[CLLocationManager alloc] init];
68
+ self.locationManager.delegate = self;
69
+ [self.locationManager requestAlwaysAuthorization];
70
+ }
71
+
72
+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
73
+ [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert + UNAuthorizationOptionSound)
74
+ completionHandler:^(BOOL granted, NSError * _Nullable error) {
75
+ if (!granted) {
76
+ NSLog(@"Notification permission not granted");
77
+ }
78
+ }];
79
+
80
+ double latitude = [dict[@"latitude"] doubleValue];
81
+ double longitude = [dict[@"longitude"] doubleValue];
82
+ double radius = [dict[@"radius"] doubleValue];
83
+ NSString *identifier = dict[@"geofenceId"];
84
+ NSString *enterMessage = dict[@"enterNotificationMsg"];
85
+ NSString *exitMessage = dict[@"exitNotificationMsg"];
86
+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
87
+ [defaults setObject:enterMessage forKey:[NSString stringWithFormat:@"%@_enterMessage", identifier]];
88
+ [defaults setObject:exitMessage forKey:[NSString stringWithFormat:@"%@_exitMessage", identifier]];
89
+ [defaults synchronize];
90
+
91
+ CLLocationCoordinate2D centerCoordinate = CLLocationCoordinate2DMake(latitude, longitude);
92
+ CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:centerCoordinate radius:radius identifier:identifier];
93
+ region.notifyOnEntry = YES;
94
+ region.notifyOnExit = YES;
95
+
96
+ [self.locationManager startMonitoringForRegion:region];
97
+
98
+ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Geofence added"];
99
+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
100
+ } @catch (NSException *exception) {
101
+ CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Failed to add geofence"];
102
+ [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
103
+ }
104
+ }
105
+
106
+ - (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
107
+ if ([region isKindOfClass:[CLCircularRegion class]]) {
108
+ [self handleEventForRegion:(CLCircularRegion *)region eventType:@"enter"];
109
+ }
110
+ }
111
+
112
+ - (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
113
+ if ([region isKindOfClass:[CLCircularRegion class]]) {
114
+ [self handleEventForRegion:(CLCircularRegion *)region eventType:@"exit"];
115
+ }
116
+ }
117
+
118
+ - (void)handleEventForRegion:(CLCircularRegion *)region eventType:(NSString *)eventType {
119
+ NSLog(@"Handling event for region: %@ with event type: %@", region.identifier, eventType);
120
+ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
121
+ NSString *messageKey = [NSString stringWithFormat:@"%@_%@Message", region.identifier, eventType];
122
+ NSString *customMessage = [defaults stringForKey:messageKey];
123
+ UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
124
+ content.title = @"Geofence Event";
125
+ content.body = customMessage ? customMessage : [NSString stringWithFormat:@"Geofence %@: %@", eventType, region.identifier];
126
+ content.sound = [UNNotificationSound defaultSound];
127
+
128
+ UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:[[NSUUID UUID] UUIDString] content:content trigger:nil];
129
+ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
130
+ [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
131
+ if (error != nil) {
132
+ NSLog(@"Error adding notification request: %@", error);
133
+ } else {
134
+ NSLog(@"Notification request added successfully");
135
+ }
136
+ }];
137
+
138
+ NSArray *components = [region.identifier componentsSeparatedByString:@"--"];
139
+ NSString *clientID = components[1];
140
+ NSString *countryCode = components[2];
141
+ NSString *userID = components[3];
142
+
143
+ NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
144
+ NSString *baseFolder = [NSString stringWithFormat:@"%@/%@/%@/%@/%@/geofence", directory, [self GetAppName], clientID, countryCode,userID];
145
+
146
+ NSString *fileName = [NSString stringWithFormat:@"%@--%@.json", region.identifier, eventType];
147
+
148
+ [self writeEventToJsonFileWithGeofenceId:region.identifier eventType:eventType folderPath:baseFolder fileName:fileName];
149
+ }
150
+
151
+ - (void)writeEventToJsonFileWithGeofenceId:(NSString *)geofenceId eventType:(NSString *)eventType folderPath:(NSString *)folderPath fileName:(NSString *)fileName {
152
+ NSDictionary *event = @{
153
+ @"eventName": eventType,
154
+ @"geofenceID": geofenceId
155
+ };
156
+
157
+ NSError *error;
158
+ NSData *jsonData = [NSJSONSerialization dataWithJSONObject:event options:NSJSONWritingPrettyPrinted error:&error];
159
+
160
+ if (!jsonData) {
161
+ NSLog(@"Error creating JSON: %@", error.localizedDescription);
162
+ return;
163
+ }
164
+ NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
165
+ NSFileManager *fileManager = [NSFileManager defaultManager];
166
+ if (![fileManager fileExistsAtPath:folderPath]) {
167
+ [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:&error];
168
+ if (error) {
169
+ NSLog(@"Error creating directory: %@", error.localizedDescription);
170
+ return;
171
+ }
172
+ }
173
+ BOOL success = [jsonData writeToFile:filePath atomically:YES];
174
+
175
+ if (success) {
176
+ NSLog(@"Successfully wrote event to file: %@", filePath);
177
+ } else {
178
+ NSLog(@"Failed to write event to file: %@", filePath);
179
+ }
180
+ NSData *jsonData1 = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
181
+
182
+ if (!jsonData1) {
183
+ NSLog(@"Error reading JSON file: %@", error.localizedDescription);
184
+
185
+ }
186
+
187
+ // Convert JSON data to a string
188
+ NSString *jsonString = [[NSString alloc] initWithData:jsonData1 encoding:NSUTF8StringEncoding];
189
+ NSLog(@"content: %@", jsonString);
190
+
191
+ }
32
192
  - (void)GetFCMUtils:(CDVInvokedUrlCommand *)command {
33
193
  OSDeviceState *deviceState = [OneSignal getDeviceState];
34
194
  NSMutableDictionary * deviceDict = [[NSMutableDictionary alloc] init];