EADemo是Apple提供的一個實現MFi的範例
它主要就是在使用EADSessionController這個Class,並且把它設定成singleton,讓程式能隨時呼叫它來做藍牙傳輸的訊息收發。
/*
@ 開始使用EADSessionController前的準備動作
*/
//先打開EAAccessoryManager的通知
//讓它能在Accessory連上與斷開時,能接到通知,觸發你要的function
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidConnect:) name:EAAccessoryDidConnectNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_accessoryDidDisconnect:) name:EAAccessoryDidDisconnectNotification object:nil];
[[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications];
//以singleton的模式呼叫EADSessionController
//讓它能在往後被程式所使用。
_eaSessionController = [EADSessionController sharedController];
//用一個陣列去接目前己連線的Accessories
//讓它能在往後被使用。
_accessoryList = [[NSMutableArray alloc] initWithArray:[[EAAccessoryManager sharedAccessoryManager] connectedAccessories]];
if ([_accessoryList count] == 0) {
//如果沒抓到已連接的裝置,執行這裡...
} else {
//如果有抓到已連接的裝置,執行這裡...
}
/*
@ 實作接到connected / disconnected通知的function
*/
#pragma mark Internal
- (void)_accessoryDidConnect:(NSNotification *)notification {
EAAccessory *connectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
[_accessoryList addObject:connectedAccessory];
if ([_accessoryList count] == 0) {
[_noExternalAccessoriesPosterView setHidden:NO];
} else {
[_noExternalAccessoriesPosterView setHidden:YES];
}
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:([_accessoryList count] - 1) inSection:0];
[[self tableView] insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
}
- (void)_accessoryDidDisconnect:(NSNotification *)notification {
EAAccessory *disconnectedAccessory = [[notification userInfo] objectForKey:EAAccessoryKey];
if (_selectedAccessory && [disconnectedAccessory connectionID] == [_selectedAccessory connectionID])
{
[_protocolSelectionActionSheet dismissWithClickedButtonIndex:-1 animated:YES];
}
int disconnectedAccessoryIndex = 0;
for(EAAccessory *accessory in _accessoryList) {
if ([disconnectedAccessory connectionID] == [accessory connectionID]) {
break;
}
disconnectedAccessoryIndex++;
}
if (disconnectedAccessoryIndex < [_accessoryList count]) {
[_accessoryList removeObjectAtIndex:disconnectedAccessoryIndex];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:disconnectedAccessoryIndex inSection:0];
[[self tableView] deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
} else {
NSLog(@"could not find disconnected accessory in accessory list");
}
if ([_accessoryList count] == 0) {
//如果沒抓到已連接的裝置,執行這裡...
} else {
//如果有抓到已連接的裝置,執行這裡...
}
}
/*
@ 準備動作做完,實際使用EADSessionController的物件來傳送封包
*/
//
- (void)setupControllerForAccessory:(EAAccessory *)accessory withProtocolString:(NSString *)protocolString;
- (BOOL)openSession;
- (void)closeSession;
- (void)writeData:(NSData *)data;
- (NSUInteger)readBytesAvailable;
- (NSData *)readData:(NSUInteger)bytesToRead;
沒有留言:
張貼留言