Note: The code on this page is for tutorial purposes only. It shows how to call the SDK and is not production-ready: it leaves out error handling, threading and app lifecycle management. Review and adapt it before you use it in your app.
Overview
A step-by-step guide to building an iOS app that connects to a Zebra RFID reader and reads tags with the Zebra RFID SDK for iOS. Each step links to the tutorial page that explains it in detail.
Details
The SDK is written in Objective-C and talks to the reader over Bluetooth. All APIs are defined by the ZebraRfidSdkFramework framework. You work with one SDK object, apiInstance, which you create once and use for every call, and you receive everything the reader reports through one delegate object.
You need:
- Xcode, and the
ZebraRfidSdkFramework.xcframeworkfrom the Zebra RFID SDK for iOS package. - A physical iPhone or iPad. The simulator has no Bluetooth, so you can build for it but you cannot connect to a reader.
- A supported reader (RFD40, RFD90 or RFD8500), paired with the iOS device in Settings > Bluetooth.
Step 1: Create the project
In Xcode, choose File > New > Project, select the iOS App template and choose Objective-C as the language. The samples in this tutorial are written in Objective-C.
Step 2: Add the SDK framework
- Drag
ZebraRfidSdkFramework.xcframeworkinto the project navigator. Select your app target when Xcode asks which targets to add it to. - Select the app target, open the General tab and find Frameworks, Libraries, and Embedded Content.
- Set the framework to Embed & Sign. The SDK is a dynamic framework, so it has to be embedded in the app or the app fails to start.
You do not need to add CoreBluetooth or ExternalAccessory: the SDK framework already links them.
If your app also uses the barcode scanner (see Initialize Barcode SDK), add ZebraScannerFramework.xcframework in the same way.
Import <ZebraRfidSdkFramework/ZebraRfidSdkFramework.h> in the files that use the SDK, as the complete example below does.
Step 3: Configure Info.plist
Add these keys to your app's Info.plist, or enter them on the Info tab of the target:
UISupportedExternalAccessoryProtocols(Supported external accessory protocols): the protocols the reader and the scanner use. Addcom.zebra.rfd8X00_easytextfor the RFID reader, andcom.zebra.scanner.SSIif you use the barcode scanner.NSBluetoothAlwaysUsageDescription(Privacy - Bluetooth Always Usage Description): the text iOS shows when it asks the user for Bluetooth access. Without it iOS can close the app when it first uses Bluetooth. AddNSBluetoothPeripheralUsageDescriptionwith the same text as well.UIBackgroundModes(Required background modes): addbluetooth-centralandexternal-accessoryonly if your app has to keep communicating with the reader while it is in the background.
<key>UISupportedExternalAccessoryProtocols</key>
<array>
<string>com.zebra.rfd8X00_easytext</string>
<string>com.zebra.scanner.SSI</string>
</array>
<key>NSBluetoothAlwaysUsageDescription</key>
<string>Uses Bluetooth to find, connect and communicate with nearby Zebra RFID readers.</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>Uses Bluetooth to find, connect and communicate with nearby Zebra RFID readers.</string>
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
<string>external-accessory</string>
</array>
Build the project. If it builds, the framework is set up correctly.
Step 4: Initialize the SDK
Create the SDK object, register your delegate and subscribe for events. Then set the operation mode and enable the detection of available readers. The delegate is your view controller, which must declare <srfidISdkApiDelegate> in its @interface (see the complete example). These pages explain each part:
- Creating the SDK Instance
- Implement srfidISdkApiDelegate
- Set Operation Mode
- Enable Available Readers Detection
Step 5: Connect to a reader
Get the list of readers with Get Available Readers, then open a session with Connect. Commands work only after the session is established and the ASCII connection is open; the Connect page explains the order. To keep the connection alive when it drops, see Enable Automatic Communication Session Reestablishment.
Step 6: Check the reader
Before you read tags, you can check which reader you are connected to and which region it is set to:
Step 7: Read tags
Reading tags is an inventory. You set when it starts and stops with the trigger settings (see Trigger Configuration), subscribe for tag events, and start it with srfidStartInventory (see Inventory). The tags arrive one by one in srfidEventReadNotify:aTagData:. To see tags you need a connected reader and tags within its range, so this step works only on a physical device with a reader.
Step 8: Disconnect
When you are done, close the session with Disconnect.
Complete example
This example puts steps 4 to 8 together on one screen: a Connect, a Disconnect and a Start/Stop button, and a text view that shows a log. It needs nothing else, so you can use it as is. Replace the contents of the ViewController.h and ViewController.m files that the Xcode template created with the code below.
In ViewController.h, the view controller declares that it implements srfidISdkApiDelegate. Without this the SDK does not accept it as the delegate and the build shows a warning.
#import <UIKit/UIKit.h>
#import <ZebraRfidSdkFramework/ZebraRfidSdkFramework.h>
@interface ViewController : UIViewController <srfidISdkApiDelegate>
@end
In ViewController.m, the view controller builds its screen, creates the SDK object (Step 4), connects when you tap Connect (Step 5), starts and stops an inventory when you tap Start/Stop (Step 7) and disconnects when you tap Disconnect (Step 8). The delegate methods at the end are the ones the SDK can call. The first four are used here; the others are empty, because srfidISdkApiDelegate needs every method to be present.
#import "ViewController.h"
@implementation ViewController {
id<srfidISdkApi> apiInstance;
int readerID;
BOOL isReading;
UITextView *logView;
UIButton *readButton;
}
#pragma mark - Screen: three buttons and a log
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = UIColor.systemBackgroundColor;
UIButton *connectButton = [self buttonWithTitle:@"Connect" action:@selector(connectTapped)];
UIButton *disconnectButton = [self buttonWithTitle:@"Disconnect" action:@selector(disconnectTapped)];
readButton = [self buttonWithTitle:@"Start" action:@selector(readTapped)];
UIStackView *buttons = [[UIStackView alloc] initWithArrangedSubviews:@[connectButton, disconnectButton, readButton]];
buttons.distribution = UIStackViewDistributionFillEqually;
buttons.translatesAutoresizingMaskIntoConstraints = NO;
logView = [[UITextView alloc] init];
logView.editable = NO;
logView.font = [UIFont monospacedSystemFontOfSize:12 weight:UIFontWeightRegular];
logView.translatesAutoresizingMaskIntoConstraints = NO;
[self.view addSubview:buttons];
[self.view addSubview:logView];
UILayoutGuide *safe = self.view.safeAreaLayoutGuide;
[NSLayoutConstraint activateConstraints:@[
[buttons.topAnchor constraintEqualToAnchor:safe.topAnchor constant:12],
[buttons.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor constant:12],
[buttons.trailingAnchor constraintEqualToAnchor:safe.trailingAnchor constant:-12],
[logView.topAnchor constraintEqualToAnchor:buttons.bottomAnchor constant:12],
[logView.leadingAnchor constraintEqualToAnchor:safe.leadingAnchor constant:12],
[logView.trailingAnchor constraintEqualToAnchor:safe.trailingAnchor constant:-12],
[logView.bottomAnchor constraintEqualToAnchor:safe.bottomAnchor constant:-12],
]];
[self setUpSdk];
}
- (UIButton *)buttonWithTitle:(NSString *)title action:(SEL)action {
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
[button setTitle:title forState:UIControlStateNormal];
[button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
return button;
}
/* shows a line in the text view and in the Xcode console */
- (void)log:(NSString *)line {
NSLog(@"%@", line);
dispatch_async(dispatch_get_main_queue(), ^{
self->logView.text = [self->logView.text stringByAppendingFormat:@"%@\n", line];
[self->logView scrollRangeToVisible:NSMakeRange(self->logView.text.length, 0)];
});
}
#pragma mark - Step 4: initialize the SDK
- (void)setUpSdk {
apiInstance = [srfidSdkFactory createRfidSdkApiInstance];
[apiInstance srfidSetDelegate:self];
[apiInstance srfidSubsribeForEvents:SRFID_EVENT_READER_APPEARANCE | SRFID_EVENT_READER_DISAPPEARANCE |
SRFID_EVENT_SESSION_ESTABLISHMENT | SRFID_EVENT_SESSION_TERMINATION];
[apiInstance srfidSubsribeForEvents:SRFID_EVENT_MASK_READ | SRFID_EVENT_MASK_STATUS];
[apiInstance srfidSetOperationalMode:SRFID_OPMODE_MFI];
[apiInstance srfidEnableAvailableReadersDetection:YES];
[self log:[NSString stringWithFormat:@"SDK version: %@", [apiInstance srfidGetSdkVersion]]];
}
#pragma mark - Step 5: connect (Connect button)
- (void)connectTapped {
NSMutableArray *availableReaders = [[NSMutableArray alloc] init];
[apiInstance srfidGetAvailableReadersList:&availableReaders];
if (availableReaders.count == 0) {
[self log:@"No reader available. Pair the reader in Settings > Bluetooth first."];
return;
}
readerID = [(srfidReaderInfo *)availableReaders[0] getReaderID];
SRFID_RESULT result = [apiInstance srfidEstablishCommunicationSession:readerID];
[self log:[NSString stringWithFormat:@"Connecting to reader %d (result %d)", readerID, result]];
}
#pragma mark - Step 7: read tags (Start/Stop button)
- (void)readTapped {
if (isReading) {
[apiInstance srfidStopInventory:readerID aStatusMessage:nil];
return;
}
/* start and stop immediately, without the handheld trigger */
srfidStartTriggerConfig *startTrigger = [[srfidStartTriggerConfig alloc] init];
[startTrigger setStartOnHandheldTrigger:NO];
[startTrigger setStartDelay:0];
[startTrigger setRepeatMonitoring:NO];
srfidStopTriggerConfig *stopTrigger = [[srfidStopTriggerConfig alloc] init];
[stopTrigger setStopOnHandheldTrigger:NO];
[stopTrigger setStopOnTimeout:NO];
[stopTrigger setStopOnTagCount:NO];
[stopTrigger setStopOnInventoryCount:NO];
[stopTrigger setStopOnAccessCount:NO];
NSString *errorResponse = nil;
SRFID_RESULT result = [apiInstance srfidSetStartTriggerConfiguration:readerID aStartTriggeConfig:startTrigger aStatusMessage:&errorResponse];
if (result == SRFID_RESULT_SUCCESS) {
result = [apiInstance srfidSetStopTriggerConfiguration:readerID aStopTriggeConfig:stopTrigger aStatusMessage:&errorResponse];
}
if (result != SRFID_RESULT_SUCCESS) {
[self log:@"Could not set the triggers. Is a reader connected?"];
return;
}
srfidReportConfig *report = [[srfidReportConfig alloc] init];
[report setIncRSSI:YES];
srfidAccessConfig *access = [[srfidAccessConfig alloc] init];
[access setPower:270];
[access setDoSelect:NO];
result = [apiInstance srfidStartInventory:readerID aMemoryBank:SRFID_MEMORYBANK_EPC aReportConfig:report aAccessConfig:access aStatusMessage:&errorResponse];
if (result != SRFID_RESULT_SUCCESS) {
[self log:[NSString stringWithFormat:@"Could not start reading: %@", errorResponse ?: @"request failed"]];
}
}
#pragma mark - Step 8: disconnect (Disconnect button)
- (void)disconnectTapped {
[apiInstance srfidTerminateCommunicationSession:readerID];
}
#pragma mark - srfidISdkApiDelegate: the methods this example uses
- (void)srfidEventCommunicationSessionEstablished:(srfidReaderInfo *)activeReader {
readerID = [activeReader getReaderID];
[self log:@"Reader connected"];
/* commands to the reader work only after the ASCII connection is established */
[apiInstance srfidEstablishAsciiConnection:readerID];
}
- (void)srfidEventCommunicationSessionTerminated:(int)terminatedReaderID {
[self log:@"Reader disconnected"];
}
- (void)srfidEventStatusNotify:(int)notifiedReaderID aEvent:(SRFID_EVENT_STATUS)event aNotification:(id)notificationData {
if (event == SRFID_EVENT_STATUS_OPERATION_START || event == SRFID_EVENT_STATUS_OPERATION_STOP) {
isReading = (event == SRFID_EVENT_STATUS_OPERATION_START);
dispatch_async(dispatch_get_main_queue(), ^{
[self->readButton setTitle:(self->isReading ? @"Stop" : @"Start") forState:UIControlStateNormal];
});
[self log:(isReading ? @"Reading started" : @"Reading stopped")];
}
}
/* every tag the reader reports arrives here */
- (void)srfidEventReadNotify:(int)notifiedReaderID aTagData:(srfidTagData *)tagData {
[self log:[NSString stringWithFormat:@"Tag: %@ RSSI: %d", [tagData getTagId], [tagData getPeakRSSI]]];
}
#pragma mark - srfidISdkApiDelegate: the rest, empty stubs
- (void)srfidEventReaderAppeared:(srfidReaderInfo *)availableReader {
}
- (void)srfidEventReaderDisappeared:(int)disappearedReaderID {
}
- (void)srfidEventProximityNotify:(int)notifiedReaderID aProximityPercent:(int)proximityPercent {
}
- (void)srfidEventMultiProximityNotify:(int)notifiedReaderID aTagData:(srfidTagData *)tagData {
}
- (void)srfidEventTriggerNotify:(int)notifiedReaderID aTriggerEvent:(SRFID_TRIGGEREVENT)triggerEvent {
}
- (void)srfidEventBatteryNotity:(int)notifiedReaderID aBatteryEvent:(srfidBatteryEvent *)batteryEvent {
}
- (void)srfidEventWifiScan:(int)notifiedReaderID wlanSCanObject:(srfidWlanScanList *)wlanScanObject {
}
- (void)srfidEventIOTSatusNotity:(int)notifiedReaderID aIOTStatusEvent:(srfidIOTStatusEvent *)iotStatusEvent {
}
- (void)srfidEventConnectedInterfaceNotity:(int)notifiedReaderID aConnectedInterfaceEvent:(sfidConnectedInterfaceEvent *)connectedInterfaceEvent {
}
@end
Build and run on a physical iPhone or iPad. To see tag reads you also need a paired reader and some RFID tags within its range. On the simulator the app starts and shows the SDK version, but it cannot connect to a reader. Tap Connect, wait for "Reader connected" in the log, and tap Start. Every tag the reader reports is logged with its tag ID and RSSI. Tap Stop to end the inventory.
If something does not work
- Build error:
ZebraRfidSdkFramework/ZebraRfidSdkFramework.hnot found. The framework is not added to your app target (Step 2). - The app closes right after it starts. The framework is not set to Embed & Sign (Step 2), or Info.plist has no Bluetooth usage description (Step 3).
- The reader is not in the list of available readers. Check that it is paired in Settings > Bluetooth, and that you set the operation mode and enabled available readers detection (Step 4).
- Build warning: sending 'ViewController' to parameter of incompatible type
id<srfidISdkApiDelegate>.ViewController.hdoes not declare<srfidISdkApiDelegate>(Step 4). - Start shows no tags. Check that "Reader connected" is in the log, that you waited for it before tapping Start, and that tags are within the range of the reader.
- Commands fail right after connecting. Wait for
srfidEventCommunicationSessionEstablished:and open the ASCII connection first (Step 5).
What's Next
- Read and change the reader's settings: Antenna Configuration, Singulation Configuration, Managing Configuration.
- Filter what you read: Pre-filters Configuration, Inventory with Pre-filters.
- Work with one tag: Read and Write, Lock, Kill, Perform Access in Sequence.
- Find a tag: Tag Locationing.
- Battery and device status: Knowing Battery Status.
- Diagnose problems: Get Reader Log.
- Use the reader's barcode scanner: Initialize Barcode SDK.