一段时间以来,我一直在努力让它发挥作用。 我已经完成了他们在文档中所说的一切,但仍然一无所获。
这是我的应用委托(delegate)中注册本地通知的代码:
- (void) registerForLocalNotifications {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_accessoryConnected:)
name:EAAccessoryDidConnectNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(_accessoryDisconnected:)
name:EAAccessoryDidDisconnectNotification
object:nil];
[[EAAccessoryManager sharedAccessoryManager] registerForLocalNotifications]; }
以上是从 applicationDidFinishLaunching 调用的。
这里是连接/断开方法的代码:
- (void) _accessoryConnected:(NSNotification *)notification {
NSLog(@"_accessoryConnected"); }
- (void) _accessoryDisconnected:(NSNotification*)notification {
NSLog(@"_accessoryDisconnected"); }
-(void) accessoryDidDisconnect:(EAAccessory *) accessory {
NSLog(@"accessoryDidDisconnect"); }
尝试连接 iPhone 附带的耳机但没有任何效果,对于我想与应用程序集成的外部配件也是如此。
请帮忙, 谢谢, 沙乌尔。
最佳答案
您应该为此使用 AudioSessionPropertyListener。 EAAccessory 通知适用于连接到 30 针端口的硬件。 在 viewDidLoad 中添加这个监听器,在 ViewDidUnLoad 中移除
AudioSessionAddPropertyListener(kAudioSessionProperty_AudioRouteChange, audioSessionPropertyListener, nil);
在 View Controller 中添加以下方法。
BOOL isHeadsetPluggedIn() {
UInt32 routeSize = sizeof (CFStringRef);
CFStringRef route;
OSStatus error = AudioSessionGetProperty (kAudioSessionProperty_AudioRoute,
&routeSize,
&route
);
NSLog(@"%@", route);
return (!error && (route != NULL) && ([(NSString*)route rangeOfString:@"Head"].location != NSNotFound));
}
void audioSessionPropertyListener(void* inClientData, AudioSessionPropertyID inID,
UInt32 inDataSize, const void* inData) {
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
// Determines the reason for the route change, to ensure that it is not
// because of a category change.
CFDictionaryRef routeChangeDictionary = inData;
CFNumberRef routeChangeReasonRef = CFDictionaryGetValue (routeChangeDictionary,CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
SInt32 routeChangeReason;
CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
// "Old device unavailable" indicates that a headset was unplugged, or that the
// device was removed from a dock connector that supports audio output.
if (routeChangeReason != kAudioSessionRouteChangeReason_OldDeviceUnavailable)
return;
if (!isHeadsetPluggedIn())
{
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
}
else
{
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof(audioRouteOverride), &audioRouteOverride);
}
}
请注意,我很久以前从某个地方得到了这段代码,它对我有用。现在无法确定来源,因为我不知道我从哪里得到的。
关于ios - 将外部配件连接到 3.5 毫米耳机插孔时无法收到通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6922898/