Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using CoreFoundation;
- using CoreNFC;
- using Foundation;
- using Poz1.NFCForms.Abstract;
- using Poz1.NFCForms.iOS;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- [assembly: Xamarin.Forms.Dependency(typeof(NfcForms))]
- namespace Poz1.NFCForms.iOS
- {
- public class NfcForms : NSObject, INfcForms, INFCNdefReaderSessionDelegate
- {
- private NFCNdefReaderSession _session;
- public event EventHandler<NfcFormsTag> TagDetected;
- public void WriteTag(NdefLibrary.Ndef.NdefMessage message)
- {
- throw new NotImplementedException();
- }
- public bool IsAvailable
- {
- get
- {
- return NFCNdefReaderSession.ReadingAvailable;
- }
- }
- //Events are declared to satisfy the interface. but they dont do anything
- public event EventHandler<NfcFormsTag> TagDisconnected;
- public event EventHandler<NfcFormsTag> TagConnected;
- public event EventHandler<NfcFormsTag> NewTag;
- //actual method that does the reading, in the android part it returns an empty string as its not used by me, could be altered
- public async Task<string> ReadTag()
- {
- var reader = new NfcReader();
- var result = await reader.ScanAsync();
- if (result != null)
- {
- return result;
- }
- else
- {
- return "No messages found";
- }
- }
- public void DidInvalidate(NFCNdefReaderSession session, NSError error)
- {
- //never got thrown when i tested with 20+ different mifare ultralights
- //throw new NotImplementedException();
- }
- public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
- {
- var bytes = messages[0].Records[0].Payload.Skip(3).ToArray();
- var message = Encoding.UTF8.GetString(bytes);
- }
- }
- public class NfcReader : NSObject, INFCNdefReaderSessionDelegate
- {
- private NFCNdefReaderSession _session;
- private TaskCompletionSource<string> _tcs;
- public Task<string> ScanAsync()
- {
- if (!NFCNdefReaderSession.ReadingAvailable)
- {
- throw new InvalidOperationException("Reading NDEF is not available");
- }
- _tcs = new TaskCompletionSource<string>();
- _session = new NFCNdefReaderSession(this, null, true);
- _session?.BeginSession();
- return _tcs.Task;
- }
- public void DidInvalidate(NFCNdefReaderSession session, NSError error)
- {
- _tcs.TrySetException(new Exception(error?.LocalizedFailureReason));
- }
- public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
- {
- var bytes = messages[0].Records[0].Payload.Skip(3).ToArray();
- var message = Encoding.UTF8.GetString(bytes);
- _tcs.SetResult(message);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement