diff --git a/README.md b/README.md index 4df50fb7..a74eff91 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -PhoneGap NFC Plugin +PhoneGap NFC Plugin (With Fix for SDK 34) ========================== The NFC plugin allows you to read and write NFC tags. You can also beam to, and receive from, other NFC enabled devices. diff --git a/package.json b/package.json index 47ea5fa9..b97e4d7b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "phonegap-nfc", - "version": "1.2.0", + "version": "1.3.0", "description": "Near Field Communication (NFC) Plugin. Read and write NDEF messages to NFC tags and share NDEF messages with peers.", "cordova": { "id": "phonegap-nfc", diff --git a/plugin.xml b/plugin.xml index d2dddbe4..14720e2e 100644 --- a/plugin.xml +++ b/plugin.xml @@ -3,7 +3,7 @@ xmlns="http://www.phonegap.com/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android" id="phonegap-nfc" - version="1.2.0"> + version="1.3.0"> NFC @@ -14,11 +14,11 @@ https://github.com/chariotsolutions/phonegap-nfc.git https://github.com/chariotsolutions/phonegap-nfc/issues - + @@ -35,14 +35,9 @@ - - - - - @@ -55,15 +50,10 @@ - - - - - @@ -89,9 +79,6 @@ - - - @@ -107,10 +94,6 @@ - - - - @@ -143,5 +126,4 @@ - diff --git a/src/android/src/com/chariotsolutions/nfc/plugin/NfcPlugin.java b/src/android/src/com/chariotsolutions/nfc/plugin/NfcPlugin.java index e8256d83..cd9b0278 100644 --- a/src/android/src/com/chariotsolutions/nfc/plugin/NfcPlugin.java +++ b/src/android/src/com/chariotsolutions/nfc/plugin/NfcPlugin.java @@ -20,12 +20,10 @@ import android.content.Intent; import android.content.IntentFilter; import android.content.IntentFilter.MalformedMimeTypeException; -import android.net.Uri; import android.nfc.FormatException; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; -import android.nfc.NfcEvent; import android.nfc.Tag; import android.nfc.TagLostException; import android.nfc.tech.Ndef; @@ -35,7 +33,7 @@ import android.os.Parcelable; import android.util.Log; -public class NfcPlugin extends CordovaPlugin implements NfcAdapter.OnNdefPushCompleteCallback { +public class NfcPlugin extends CordovaPlugin { private static final String REGISTER_MIME_TYPE = "registerMimeType"; private static final String REMOVE_MIME_TYPE = "removeMimeType"; private static final String REGISTER_NDEF = "registerNdef"; @@ -46,10 +44,6 @@ public class NfcPlugin extends CordovaPlugin implements NfcAdapter.OnNdefPushCom private static final String WRITE_TAG = "writeTag"; private static final String MAKE_READ_ONLY = "makeReadOnly"; private static final String ERASE_TAG = "eraseTag"; - private static final String SHARE_TAG = "shareTag"; - private static final String UNSHARE_TAG = "unshareTag"; - private static final String HANDOVER = "handover"; // Android Beam - private static final String STOP_HANDOVER = "stopHandover"; private static final String ENABLED = "enabled"; private static final String INIT = "init"; private static final String SHOW_SETTINGS = "showSettings"; @@ -74,21 +68,17 @@ public class NfcPlugin extends CordovaPlugin implements NfcAdapter.OnNdefPushCom private static final String STATUS_NFC_OK = "NFC_OK"; private static final String STATUS_NO_NFC = "NO_NFC"; private static final String STATUS_NFC_DISABLED = "NFC_DISABLED"; - private static final String STATUS_NDEF_PUSH_DISABLED = "NDEF_PUSH_DISABLED"; private static final String TAG = "NfcPlugin"; private final List intentFilters = new ArrayList<>(); private final ArrayList techLists = new ArrayList<>(); - private NdefMessage p2pMessage = null; private PendingIntent pendingIntent = null; private Intent savedIntent = null; private CallbackContext readerModeCallback; private CallbackContext channelCallback; - private CallbackContext shareTagCallback; - private CallbackContext handoverCallback; @Override public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException { @@ -155,18 +145,6 @@ public boolean execute(String action, JSONArray data, CallbackContext callbackCo } else if (action.equalsIgnoreCase(ERASE_TAG)) { eraseTag(callbackContext); - } else if (action.equalsIgnoreCase(SHARE_TAG)) { - shareTag(data, callbackContext); - - } else if (action.equalsIgnoreCase(UNSHARE_TAG)) { - unshareTag(callbackContext); - - } else if (action.equalsIgnoreCase(HANDOVER)) { - handover(data, callbackContext); - - } else if (action.equalsIgnoreCase(STOP_HANDOVER)) { - stopHandover(callbackContext); - } else if (action.equalsIgnoreCase(INIT)) { init(callbackContext); @@ -289,13 +267,6 @@ private void removeNdef(CallbackContext callbackContext) { callbackContext.success(); } - private void unshareTag(CallbackContext callbackContext) { - p2pMessage = null; - stopNdefPush(); - shareTagCallback = null; - callbackContext.success(); - } - private void init(CallbackContext callbackContext) { Log.d(TAG, "Enabling plugin " + getIntent()); @@ -438,43 +409,13 @@ private void makeReadOnly(final CallbackContext callbackContext) { }); } - private void shareTag(JSONArray data, CallbackContext callbackContext) throws JSONException { - NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0)); - this.p2pMessage = new NdefMessage(records); - - startNdefPush(callbackContext); - } - - // setBeamPushUris - // Every Uri you provide must have either scheme 'file' or scheme 'content'. - // Note that this takes priority over setNdefPush - // - // See http://developer.android.com/reference/android/nfc/NfcAdapter.html#setBeamPushUris(android.net.Uri[],%20android.app.Activity) - private void handover(JSONArray data, CallbackContext callbackContext) throws JSONException { - - Uri[] uri = new Uri[data.length()]; - - for (int i = 0; i < data.length(); i++) { - uri[i] = Uri.parse(data.getString(i)); - } - - startNdefBeam(callbackContext, uri); - } - - private void stopHandover(CallbackContext callbackContext) { - stopNdefBeam(); - handoverCallback = null; - callbackContext.success(); - } - private void showSettings(CallbackContext callbackContext) { - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) { - Intent intent = new Intent(android.provider.Settings.ACTION_NFC_SETTINGS); - getActivity().startActivity(intent); - } else { - Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS); - getActivity().startActivity(intent); - } + Intent intent = new Intent( + android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN ? + android.provider.Settings.ACTION_NFC_SETTINGS : + android.provider.Settings.ACTION_WIRELESS_SETTINGS + ); + getActivity().startActivity(intent); callbackContext.success(); } @@ -483,7 +424,10 @@ private void createPendingIntent() { Activity activity = getActivity(); Intent intent = new Intent(activity, activity.getClass()); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); - pendingIntent = PendingIntent.getActivity(activity, 0, intent, 0); + pendingIntent = PendingIntent.getActivity( + activity, 0, intent, + android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S ? PendingIntent.FLAG_MUTABLE : 0 + ); } } @@ -546,9 +490,6 @@ private void startNfc() { nfcAdapter.enableForegroundDispatch(getActivity(), getPendingIntent(), intentFilters, techLists); } - if (p2pMessage != null) { - nfcAdapter.setNdefPushMessage(p2pMessage, getActivity()); - } } catch (IllegalStateException e) { // issue 110 - user exits app with home button while nfc is initializing Log.w(TAG, "Illegal State Exception starting NFC. Assuming application is terminating."); @@ -575,77 +516,6 @@ private void stopNfc() { }); } - private void startNdefBeam(final CallbackContext callbackContext, final Uri[] uris) { - getActivity().runOnUiThread(() -> { - - NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); - - if (nfcAdapter == null) { - callbackContext.error(STATUS_NO_NFC); - } else if (!nfcAdapter.isNdefPushEnabled()) { - callbackContext.error(STATUS_NDEF_PUSH_DISABLED); - } else { - nfcAdapter.setOnNdefPushCompleteCallback(NfcPlugin.this, getActivity()); - try { - nfcAdapter.setBeamPushUris(uris, getActivity()); - - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); - result.setKeepCallback(true); - handoverCallback = callbackContext; - callbackContext.sendPluginResult(result); - - } catch (IllegalArgumentException e) { - callbackContext.error(e.getMessage()); - } - } - }); - } - - private void startNdefPush(final CallbackContext callbackContext) { - getActivity().runOnUiThread(() -> { - - NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); - - if (nfcAdapter == null) { - callbackContext.error(STATUS_NO_NFC); - } else if (!nfcAdapter.isNdefPushEnabled()) { - callbackContext.error(STATUS_NDEF_PUSH_DISABLED); - } else { - nfcAdapter.setNdefPushMessage(p2pMessage, getActivity()); - nfcAdapter.setOnNdefPushCompleteCallback(NfcPlugin.this, getActivity()); - - PluginResult result = new PluginResult(PluginResult.Status.NO_RESULT); - result.setKeepCallback(true); - shareTagCallback = callbackContext; - callbackContext.sendPluginResult(result); - } - }); - } - - private void stopNdefPush() { - getActivity().runOnUiThread(() -> { - - NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); - - if (nfcAdapter != null) { - nfcAdapter.setNdefPushMessage(null, getActivity()); - } - - }); - } - - private void stopNdefBeam() { - getActivity().runOnUiThread(() -> { - - NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity()); - - if (nfcAdapter != null) { - nfcAdapter.setBeamPushUris(null, getActivity()); - } - - }); - } - private void addToTechList(String[] techs) { techLists.add(techs); } @@ -835,22 +705,6 @@ private void setIntent(Intent intent) { getActivity().setIntent(intent); } - @Override - public void onNdefPushComplete(NfcEvent event) { - - // handover (beam) take precedence over share tag (ndef push) - if (handoverCallback != null) { - PluginResult result = new PluginResult(PluginResult.Status.OK, "Beamed Message to Peer"); - result.setKeepCallback(true); - handoverCallback.sendPluginResult(result); - } else if (shareTagCallback != null) { - PluginResult result = new PluginResult(PluginResult.Status.OK, "Shared Message with Peer"); - result.setKeepCallback(true); - shareTagCallback.sendPluginResult(result); - } - - } - /** * Enable I/O operations to the tag from this TagTechnology object. * * diff --git a/src/ios/NfcPlugin.m b/src/ios/NfcPlugin.m index 9b40f251..58bf8903 100644 --- a/src/ios/NfcPlugin.m +++ b/src/ios/NfcPlugin.m @@ -30,7 +30,7 @@ - (void)pluginInitialize { NSLog(@"(c) 2017-2020 Don Coleman"); [super pluginInitialize]; - + if (@available(iOS 11, *)) { if (![NFCNDEFReaderSession readingAvailable]) { NSLog(@"NFC Support is NOT available"); @@ -90,22 +90,22 @@ - (void)scanTag:(CDVInvokedUrlCommand*)command { - (void)writeTag:(CDVInvokedUrlCommand*)command API_AVAILABLE(ios(13.0)){ NSLog(@"writeTag"); - + self.writeMode = YES; self.shouldUseTagReaderSession = NO; BOOL reusingSession = NO; - + NSArray *ndefData = [command argumentAtIndex:0]; // Create the NDEF Message NSMutableArray *payloads = [NSMutableArray new]; - + @try { for (id recordData in ndefData) { NSNumber *tnfNumber = [recordData objectForKey:@"tnf"]; NFCTypeNameFormat tnf = (uint8_t)[tnfNumber intValue]; NSData *type = [self uint8ArrayToNSData:[recordData objectForKey:@"type"]]; - NSData *identifier = [self uint8ArrayToNSData:[recordData objectForKey:@"identifiers"]]; + NSData *identifier = [self uint8ArrayToNSData:[recordData objectForKey:@"id"]]; NSData *payload = [self uint8ArrayToNSData:[recordData objectForKey:@"payload"]]; NFCNDEFPayload *record = [[NFCNDEFPayload alloc] initWithFormat:tnf type:type identifier:identifier payload:payload]; [payloads addObject:record]; @@ -125,17 +125,17 @@ - (void)writeTag:(CDVInvokedUrlCommand*)command API_AVAILABLE(ios(13.0)){ if (self.shouldUseTagReaderSession) { NSLog(@"Using NFCTagReaderSession"); - self.nfcSession = [[NFCTagReaderSession new] - initWithPollingOption:(NFCPollingISO14443 | NFCPollingISO15693) + self.nfcSession = [[NFCTagReaderSession alloc] + initWithPollingOption:(NFCPollingISO14443 | NFCPollingISO15693 | NFCPollingISO18092) delegate:self queue:dispatch_get_main_queue()]; } else { NSLog(@"Using NFCTagReaderSession"); - self.nfcSession = [[NFCNDEFReaderSession new]initWithDelegate:self queue:nil invalidateAfterFirstRead:FALSE]; + self.nfcSession = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:nil invalidateAfterFirstRead:FALSE]; } } - self.nfcSession.alertMessage = @"Hold near writable NFC tag to update."; + self.nfcSession.alertMessage = [self localizeString:@"NFCHoldNearWritableTag" defaultValue:@"Hold near writable NFC tag to update."]; sessionCallbackId = [command.callbackId copy]; if (reusingSession) { // reusing a read session to write @@ -160,7 +160,7 @@ - (void)cancelScan:(CDVInvokedUrlCommand*)command API_AVAILABLE(ios(11.0)){ - (void)invalidateSession:(CDVInvokedUrlCommand*)command { NSLog(@"invalidateSession"); NSLog(@"WARNING: invalidateSession is deprecated. Use cancelScan."); - + if (_nfcSession) { [_nfcSession invalidateSession]; } @@ -203,8 +203,8 @@ - (void)enabled:(CDVInvokedUrlCommand *)command { // iOS 11 & 12 - (void) readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray *)messages API_AVAILABLE(ios(11.0)) { NSLog(@"NFCNDEFReaderSession didDetectNDEFs"); - - session.alertMessage = @"Tag successfully read."; + + session.alertMessage = [self localizeString:@"NFCTagRead" defaultValue:@"Tag successfully read."]; for (NFCNDEFMessage *message in messages) { [self fireNdefEvent: message]; } @@ -212,28 +212,28 @@ - (void) readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray> *)tags API_AVAILABLE(ios(13.0)) { - + if (tags.count > 1) { - session.alertMessage = @"More than 1 tag detected. Please remove all tags and try again."; + session.alertMessage = [self localizeString:@"NFCMoreThanOneTag" defaultValue:@"More than 1 tag detected. Please remove all tags and try again."]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 500 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ NSLog(@"restaring polling"); [session restartPolling]; }); return; } - + id tag = [tags firstObject]; - + [session connectToTag:tag completionHandler:^(NSError * _Nullable error) { if (error) { NSLog(@"%@", error); - [self closeSession:session withError:@"Error connecting to tag."]; + [self closeSession:session withError:[self localizeString:@"NFCErrorTagConnection" defaultValue:@"Error connecting to tag."]]; return; } - + [self processNDEFTag:session tag:tag]; }]; - + } - (void) readerSession:(NFCNDEFReaderSession *)session didInvalidateWithError:(NSError *)error API_AVAILABLE(ios(11.0)) { @@ -260,24 +260,24 @@ - (void)tagReaderSessionDidBecomeActive:(NFCTagReaderSession *)session API_AVAIL - (void)tagReaderSession:(NFCTagReaderSession *)session didDetectTags:(NSArray<__kindof id> *)tags API_AVAILABLE(ios(13.0)) { NSLog(@"tagReaderSession didDetectTags"); - + if (tags.count > 1) { - session.alertMessage = @"More than 1 tag detected. Please remove all tags and try again."; + session.alertMessage = [self localizeString:@"NFCMoreThanOneTag" defaultValue:@"More than 1 tag detected. Please remove all tags and try again."]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 500 * NSEC_PER_MSEC), dispatch_get_main_queue(), ^{ NSLog(@"restaring polling"); [session restartPolling]; }); return; } - + id tag = [tags firstObject]; NSMutableDictionary *tagMetaData = [self getTagInfo:tag]; id ndefTag = (id)tag; - + [session connectToTag:tag completionHandler:^(NSError * _Nullable error) { if (error) { NSLog(@"%@", error); - [self closeSession:session withError:@"Error connecting to tag."]; + [self closeSession:session withError:[self localizeString:@"NFCErrorTagConnection" defaultValue:@"Error connecting to tag."]]; return; } @@ -294,34 +294,34 @@ - (void)tagReaderSession:(NFCTagReaderSession *)session didInvalidateWithError:( // Handles scanNdef, scanTag, and beginSession - (void)startScanSession:(CDVInvokedUrlCommand*)command { - + self.writeMode = NO; - + NSLog(@"shouldUseTagReaderSession %d", self.shouldUseTagReaderSession); NSLog(@"callbackOnSessionStart %d", self.sendCallbackOnSessionStart); NSLog(@"returnTagInCallback %d", self.returnTagInCallback); NSLog(@"returnTagInEvent %d", self.returnTagInEvent); - + if (@available(iOS 13.0, *)) { - + if (self.shouldUseTagReaderSession) { NSLog(@"Using NFCTagReaderSession"); - self.nfcSession = [[NFCTagReaderSession new] - initWithPollingOption:(NFCPollingISO14443 | NFCPollingISO15693) + self.nfcSession = [[NFCTagReaderSession alloc] + initWithPollingOption:(NFCPollingISO14443 | NFCPollingISO15693 | NFCPollingISO18092) delegate:self queue:dispatch_get_main_queue()]; } else { NSLog(@"Using NFCNDEFReaderSession"); - self.nfcSession = [[NFCNDEFReaderSession new]initWithDelegate:self queue:nil invalidateAfterFirstRead:TRUE]; + self.nfcSession = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:nil invalidateAfterFirstRead:TRUE]; } sessionCallbackId = [command.callbackId copy]; - self.nfcSession.alertMessage = @"Hold near NFC tag to scan."; + self.nfcSession.alertMessage = [self localizeString:@"NFCHoldNearTag" defaultValue:@"Hold near NFC tag to scan."]; [self.nfcSession beginSession]; - + } else if (@available(iOS 11.0, *)) { NSLog(@"iOS < 13, using NFCNDEFReaderSession"); - self.nfcSession = [[NFCNDEFReaderSession new]initWithDelegate:self queue:nil invalidateAfterFirstRead:TRUE]; + self.nfcSession = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:nil invalidateAfterFirstRead:TRUE]; sessionCallbackId = [command.callbackId copy]; - self.nfcSession.alertMessage = @"Hold near NFC tag to scan."; + self.nfcSession.alertMessage = [self localizeString:@"NFCHoldNearTag" defaultValue:@"Hold near NFC tag to scan."]; [self.nfcSession beginSession]; } else { NSLog(@"iOS < 11, no NFC support"); @@ -329,7 +329,7 @@ - (void)startScanSession:(CDVInvokedUrlCommand*)command { pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"NFC requires iOS 11"]; [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } - + } - (void)processNDEFTag: (NFCReaderSession *)session tag:(__kindof id)tag API_AVAILABLE(ios(13.0)) { @@ -337,14 +337,14 @@ - (void)processNDEFTag: (NFCReaderSession *)session tag:(__kindof id } - (void)processNDEFTag: (NFCReaderSession *)session tag:(__kindof id)tag metaData: (NSMutableDictionary * _Nonnull)metaData API_AVAILABLE(ios(13.0)) { - + [tag queryNDEFStatusWithCompletionHandler:^(NFCNDEFStatus status, NSUInteger capacity, NSError * _Nullable error) { if (error) { NSLog(@"%@", error); - [self closeSession:session withError:@"Error getting tag status."]; + [self closeSession:session withError:[self localizeString:@"NFCErrorTagStatus" defaultValue:@"Error getting tag status."]]; return; } - + if (self.writeMode) { [self writeNDEFTag:session status:status tag:tag]; } else { @@ -360,30 +360,30 @@ - (void)processNDEFTag: (NFCReaderSession *)session tag:(__kindof id } - (void)readNDEFTag:(NFCReaderSession * _Nonnull)session status:(NFCNDEFStatus)status tag:(id)tag metaData:(NSMutableDictionary * _Nonnull)metaData API_AVAILABLE(ios(13.0)){ - + if (status == NFCNDEFStatusNotSupported) { NSLog(@"Tag does not support NDEF"); [self fireTagEvent:metaData]; [self closeSession:session]; return; } - + if (status == NFCNDEFStatusReadOnly) { metaData[@"isWritable"] = @FALSE; } else if (status == NFCNDEFStatusReadWrite) { metaData[@"isWritable"] = @TRUE; } - + [tag readNDEFWithCompletionHandler:^(NFCNDEFMessage * _Nullable message, NSError * _Nullable error) { // Error Code=403 "NDEF tag does not contain any NDEF message" is not an error for this plugin if (error && error.code != 403) { NSLog(@"%@", error); - [self closeSession:session withError:@"Read Failed."]; + [self closeSession:session withError:[self localizeString:@"NFCDataReadFailed" defaultValue:@"Read Failed."]]; return; } else { NSLog(@"%@", message); - session.alertMessage = @"Tag successfully read."; + session.alertMessage = [self localizeString:@"NFCTagRead" defaultValue:@"Tag successfully read."]; [self fireNdefEvent:message metaData:metaData]; [self closeSession:session]; } @@ -395,29 +395,29 @@ - (void)readNDEFTag:(NFCReaderSession * _Nonnull)session status:(NFCNDEFStatus)s - (void)writeNDEFTag:(NFCReaderSession * _Nonnull)session status:(NFCNDEFStatus)status tag:(id)tag API_AVAILABLE(ios(13.0)){ switch (status) { case NFCNDEFStatusNotSupported: - [self closeSession:session withError:@"Tag is not NDEF compliant."]; // alternate message "Tag does not support NDEF." + [self closeSession:session withError:[self localizeString:@"NFCNotNdefCompliant" defaultValue:@"Tag is not NDEF compliant."]]; // alternate message "Tag does not support NDEF." break; case NFCNDEFStatusReadOnly: - [self closeSession:session withError:@"Tag is read only."]; + [self closeSession:session withError:[self localizeString:@"NFCReadOnlyTag" defaultValue:@"Tag is read only."]]; break; case NFCNDEFStatusReadWrite: { - + [tag writeNDEF: self.messageToWrite completionHandler:^(NSError * _Nullable error) { if (error) { NSLog(@"%@", error); - [self closeSession:session withError:@"Write failed."]; + [self closeSession:session withError:[self localizeString:@"NFCDataWriteFailed" defaultValue:@"Write failed."]]; } else { - session.alertMessage = @"Wrote data to NFC tag."; + session.alertMessage = [self localizeString:@"NFCDataWrote" defaultValue:@"Wrote data to NFC tag."]; CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK]; [self.commandDelegate sendPluginResult:pluginResult callbackId:self->sessionCallbackId]; [self closeSession:session]; } }]; break; - + } default: - [self closeSession:session withError:@"Unknown NDEF tag status."]; + [self closeSession:session withError:[self localizeString:@"NFCUnknownNdefTag" defaultValue:@"Unknown NDEF tag status."]]; } } @@ -425,12 +425,12 @@ - (void)writeNDEFTag:(NFCReaderSession * _Nonnull)session status:(NFCNDEFStatus) // Gets the tag meta data - type and uid - (NSMutableDictionary *) getTagInfo:(id)tag API_AVAILABLE(ios(13.0)) { - + NSMutableDictionary *tagInfo = [NSMutableDictionary new]; - + NSData *uid; NSString *type; - + switch (tag.type) { case NFCTagTypeFeliCa: type = @"NFCTagTypeFeliCa"; @@ -453,9 +453,9 @@ - (NSMutableDictionary *) getTagInfo:(id)tag API_AVAILABLE(ios(13.0)) { uid = nil; break; } - + NSLog(@"getTagInfo: %@ with uid %@", type, uid); - + [tagInfo setValue:type forKey:@"type"]; if (uid) { [tagInfo setValue:uid forKey:@"id"]; @@ -503,7 +503,7 @@ - (void) closeSession:(NFCReaderSession *) session withError:(NSString *) errorM sessionCallbackId = NULL; connectedTag = NULL; connectedTagStatus = NFCNDEFStatusNotSupported; - + if (@available(iOS 13.0, *)) { [session invalidateSessionWithErrorMessage:errorMessage]; } else { @@ -523,7 +523,7 @@ -(void) fireNdefEvent:(NFCNDEFMessage *) ndefMessage API_AVAILABLE(ios(11.0)) { // TODO rename method since we're using the channel or callback instead of firing an event -(void) fireNdefEvent:(NFCNDEFMessage *) ndefMessage metaData:(NSDictionary *)metaData API_AVAILABLE(ios(11.0)) { NSLog(@"fireNdefEvent"); - + NSMutableDictionary *nfcEvent = [NSMutableDictionary new]; nfcEvent[@"type"] = @"ndef"; nfcEvent[@"tag"] = [self buildTagDictionary:ndefMessage metaData:metaData]; @@ -535,10 +535,10 @@ -(void) fireNdefEvent:(NFCNDEFMessage *) ndefMessage metaData:(NSDictionary *)me [self.commandDelegate sendPluginResult:pluginResult callbackId:sessionCallbackId]; sessionCallbackId = NULL; } - + if (channelCallbackId && self.returnTagInEvent) { NSLog(@"Sending NFC data via channelCallbackId so an NDEF event fires)"); - + CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:nfcEvent]; [pluginResult setKeepCallback:[NSNumber numberWithBool:YES]]; [self.commandDelegate sendPluginResult:pluginResult callbackId:channelCallbackId]; @@ -548,9 +548,9 @@ -(void) fireNdefEvent:(NFCNDEFMessage *) ndefMessage metaData:(NSDictionary *)me // NSDictionary representing an NFC tag // NSData fields are converted to uint8_t arrays -(NSDictionary *) buildTagDictionary:(NFCNDEFMessage *) ndefMessage metaData: (NSDictionary *)metaData API_AVAILABLE(ios(11.0)) { - + NSMutableDictionary *dictionary = [NSMutableDictionary new]; - + // start with tag meta data if (metaData) { [dictionary setDictionary:metaData]; @@ -561,7 +561,7 @@ -(NSDictionary *) buildTagDictionary:(NFCNDEFMessage *) ndefMessage metaData: (N if (uid) { dictionary[@"id"] = [self uint8ArrayFromNSData: uid]; } - + if (ndefMessage) { NSMutableArray *array = [NSMutableArray new]; for (NFCNDEFPayload *record in ndefMessage.records){ @@ -570,7 +570,7 @@ -(NSDictionary *) buildTagDictionary:(NFCNDEFMessage *) ndefMessage metaData: (N } [dictionary setObject:array forKey:@"ndefMessage"]; } - + return [dictionary copy]; } @@ -596,7 +596,7 @@ - (NSArray *) uint8ArrayFromNSData:(NSData *) data { - (NSData *) uint8ArrayToNSData:(NSArray *) array { // NSLog(@"nsDataFromUint8Array input %@", array); - + NSMutableData *data = [[NSMutableData alloc] initWithCapacity: [array count]]; for (NSNumber *number in array) { uint8_t b = (uint8_t)[number unsignedIntValue]; @@ -619,4 +619,8 @@ - (NSString*) dictionaryAsJSONString:(NSDictionary *)dict { return jsonString; } +- (NSString*) localizeString:(NSString *)key defaultValue:(NSString*) defaultValue { + return NSLocalizedString(key, comment: "") != key ? NSLocalizedString(key, comment: "") : defaultValue; +} + @end diff --git a/src/windows/nfc-plugin.js b/src/windows/nfc-plugin.js index 687b0991..001301c4 100644 --- a/src/windows/nfc-plugin.js +++ b/src/windows/nfc-plugin.js @@ -35,7 +35,7 @@ var self = { var kludge = self.proximityDevice.maxMessageBytes; self.proximityDeviceStatus = STATUS_NFC_OK; } catch (e) { - console.log(e); + console.error(e); self.proximityDeviceStatus = STATUS_NFC_DISABLED; } return self.proximityDeviceStatus === STATUS_NFC_OK; @@ -47,7 +47,7 @@ var self = { // TODO use these events to implement nfc.addTagDiscoveredListener if (self.proximityDevice) { self.proximityDevice.ondevicearrived = function (eventArgs) { - console.log("NFC tag detected"); + console.debug("NFC tag detected"); if (self.listeningForNonNdefTags) { // set a timeout so NDEF tags can cancel this event // we want one event to mimic the Android behavior @@ -56,7 +56,7 @@ var self = { }; self.proximityDevice.ondevicedeparted = function (eventArgs) { - console.log("NFC tag is gone"); + console.debug("NFC tag is gone"); }; } else { self.proximityDeviceStatus = STATUS_NO_NFC_OR_NFC_DISABLED; @@ -69,13 +69,13 @@ var self = { self.initializeProximityDevice(); if (!self.proximityDevice) { - console.log("WARNING: proximity device is null"); + console.warn("WARNING: proximity device is null"); } success(); }, registerNdef: function (success, failure, args) { - console.log("Listening for NFC tags with NDEF messages."); + console.debug("Listening for NFC tags with NDEF messages."); if (!self.initializeProximityDevice()) { failure(self.proximityDeviceStatus); @@ -86,13 +86,13 @@ var self = { self.subscribedMessageId = self.proximityDevice.subscribeForMessage("NDEF", self.messageReceivedHandler); success(); } catch (e) { - console.log(e); + console.error(e); failure(e); } }, removeNdef: function (success, failure, args) { - console.log("Removing NDEF Listener"); + console.debug("Removing NDEF Listener"); if (!self.initializeProximityDevice()) { failure(self.proximityDeviceStatus); @@ -107,7 +107,7 @@ var self = { success(); } catch (e) { - console.log(e); + console.error(e); failure(e.message); } }, @@ -121,7 +121,7 @@ var self = { }, writeTag: function (success, failure, args) { - console.log("Write Tag"); + console.debug("Write Tag"); if (!self.initializeProximityDevice()) { failure(self.proximityDeviceStatus); @@ -141,7 +141,7 @@ var self = { self.publishedMessageId = self.proximityDevice.publishBinaryMessage("NDEF:WriteTag", dataWriter.detachBuffer(), function (sender, messageId) { - console.log("Successfully wrote message to the NFC tag."); + console.debug("Successfully wrote message to the NFC tag."); self.stopPublishing(); success(); @@ -149,13 +149,13 @@ var self = { ); } catch (e) { - console.log(e); + console.error(e); failure(e.message); } }, shareTag: function(success, failure, args) { - console.log("Share Tag"); + console.debug("Share Tag"); if (!self.initializeProximityDevice()) { failure(self.proximityDeviceStatus); @@ -175,19 +175,19 @@ var self = { self.publishedMessageId = self.proximityDevice.publishBinaryMessage("NDEF", dataWriter.detachBuffer(), function (sender, messageId) { - console.log("Successfully shared message over peer-to-peer."); + console.debug("Successfully shared message over peer-to-peer."); self.stopPublishing(); success(); }); } catch (e) { - console.log(e); + console.error(e); failure(e.message); } }, unshareTag: function(success, failure, args) { - console.log("Unshare Tag"); + console.debug("Unshare Tag"); if (!self.initializeProximityDevice()) { failure(self.proximityDeviceStatus); @@ -198,7 +198,7 @@ var self = { self.stopPublishing(); success(); } catch (e) { - console.log(e); + console.error(e); failure(e.message); } }, @@ -246,7 +246,6 @@ var self = { var byteArray = ndefUtils.toArray(bytes); var ndefMessage = ndef.decodeMessage(byteArray); - console.log(JSON.stringify(ndefMessage)); // on windows, tag only contains the ndef message // other platforms have tag data diff --git a/www/phonegap-nfc.js b/www/phonegap-nfc.js index 7349bb7a..0cf0f18f 100644 --- a/www/phonegap-nfc.js +++ b/www/phonegap-nfc.js @@ -14,10 +14,10 @@ function handleNfcFromIntentFilter() { function () { cordova.exec( function () { - console.log("Initialized the NfcPlugin"); + console.debug("Initialized the NfcPlugin"); }, function (reason) { - console.log("Failed to initialize the NfcPlugin " + reason); + console.warn("Failed to initialize the NfcPlugin " + reason); }, "NfcPlugin", "init", [] ); @@ -175,7 +175,7 @@ var ndef = { payload = ndefRecords; } } else { - console.log("WARNING: Expecting an array of NDEF records"); + console.warn("WARNING: Expecting an array of NDEF records"); } return ndef.record(ndef.TNF_WELL_KNOWN, ndef.RTD_SMART_POSTER, id, payload); @@ -410,7 +410,7 @@ var ndef = { // nfc provides javascript wrappers to the native phonegap implementation var nfc = { - + multiCallbackTest: function(success, failure) { cordova.exec(success, failure, "NfcPlugin", "multiCallbackTest", []); }, @@ -419,7 +419,7 @@ var nfc = { // //cordova.exec(success, failure, "NfcPlugin", "multiCallbackTest", []); // setInterval(failure, 10000, 'Test from JavaScript!'); // }, - + addTagDiscoveredListener: function (callback, win, fail) { document.addEventListener("tag", callback, false); cordova.exec(win, fail, "NfcPlugin", "registerTag", []); @@ -440,10 +440,10 @@ var nfc = { cordova.exec(win, fail, "NfcPlugin", "registerNdefFormatable", []); }, - write: function (ndefMessage, win, fail, options) { - + write: function (ndefMessage, win, fail, options) { + if (cordova.platformId === "ios") { - cordova.exec(win, fail, "NfcPlugin", "writeTag", [ndefMessage, options]); + cordova.exec(win, fail, "NfcPlugin", "writeTag", [ndefMessage, options]); } else { cordova.exec(win, fail, "NfcPlugin", "writeTag", [ndefMessage]); } @@ -461,18 +461,6 @@ var nfc = { cordova.exec(win, fail, "NfcPlugin", "unshareTag", []); }, - handover: function (uris, win, fail) { - // if we get a single URI, wrap it in an array - if (!Array.isArray(uris)) { - uris = [ uris ]; - } - cordova.exec(win, fail, "NfcPlugin", "handover", uris); - }, - - stopHandover: function (win, fail) { - cordova.exec(win, fail, "NfcPlugin", "stopHandover", []); - }, - erase: function (win, fail) { cordova.exec(win, fail, "NfcPlugin", "eraseTag", [[]]); }, @@ -513,7 +501,7 @@ var nfc = { cordova.exec(resolve, reject, "NfcPlugin", "scanTag", [options]); }); }, - + // iOS only - cancel NFC scan session cancelScan: function () { return new Promise(function(resolve, reject) { @@ -566,7 +554,7 @@ var nfc = { }); }, - // Android NfcAdapter.enableReaderMode flags + // Android NfcAdapter.enableReaderMode flags FLAG_READER_NFC_A: 0x1, FLAG_READER_NFC_B: 0x2, FLAG_READER_NFC_F: 0x4, @@ -574,7 +562,7 @@ var nfc = { FLAG_READER_NFC_BARCODE: 0x10, FLAG_READER_SKIP_NDEF_CHECK: 0x80, FLAG_READER_NO_PLATFORM_SOUNDS: 0x100, - + // Android NfcAdapter.enabledReaderMode readerMode: function(flags, readCallback, errorCallback) { cordova.exec(readCallback, errorCallback, 'NfcPlugin', 'readerMode', [flags]); @@ -735,7 +723,7 @@ var util = { * Convert an ArrayBuffer to a hex string * * @param {ArrayBuffer} buffer - * @returns {srting} - hex representation of bytes e.g. 000407AF + * @returns {string} - hex representation of bytes e.g. 000407AF */ arrayBufferToHexString: function(buffer) { function toHexString(byte) { @@ -764,13 +752,13 @@ var util = { // ensure even number of characters if (hexString.length % 2 != 0) { - console.log('WARNING: expecting an even number of characters in the hexString'); + console.warn('WARNING: expecting an even number of characters in the hexString'); } // check for some non-hex characters var bad = hexString.match(/[G-Z\s]/i); if (bad) { - console.log('WARNING: found non-hex characters', bad); + console.warn('WARNING: found non-hex characters', bad); } // split the string into pairs of octets @@ -796,7 +784,7 @@ var textHelper = { // TODO need to deal with UTF in the future if (utf16) { - console.log('WARNING: utf-16 data may not be handled properly for', languageCode); + console.warn('WARNING: utf-16 data may not be handled properly for', languageCode); } // Use TextDecoder when we have enough browser support // new TextDecoder('utf-8').decode(data.slice(languageCodeLength + 1)); @@ -873,7 +861,6 @@ function fireNfcTagEvent(eventType, tagAsJson) { var e = document.createEvent('Events'); e.initEvent(eventType, true, false); e.tag = JSON.parse(tagAsJson); - console.log(e.tag); document.dispatchEvent(e); }, 10); } @@ -894,15 +881,15 @@ window.ndef = ndef; window.util = util; window.fireNfcTagEvent = fireNfcTagEvent; -// This channel receives nfcEvent data from native code +// This channel receives nfcEvent data from native code // and fires JavaScript events. require('cordova/channel').onCordovaReady.subscribe(function() { require('cordova/exec')(success, null, 'NfcPlugin', 'channel', []); function success(message) { - if (!message.type) { - console.log(message); + if (!message.type) { + console.warn("Skip received NFC data, missing type in", message); } else { - console.log("Received NFC data, firing '" + message.type + "' event"); + console.debug("Received NFC data, firing '" + message.type + "' event"); var e = document.createEvent('Events'); e.initEvent(message.type); e.tag = message.tag;