Search code examples
iosaudioios-keyboard-extension

Playing system click sound in iOS keyboard extension


I have followed the instructions on both these links:

How to play keyboard click sound in custom keyboard?

https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/InputViews/InputViews.html

and done the following:

header:

@interface Key : UIView <UIInputViewAudioFeedback>

implementation:

- (BOOL) enableInputClicksWhenVisible {
    return YES;
}

- (void)tapped:(UITapGestureRecognizer *)sender
{
    [[UIDevice currentDevice] playInputClick];
    [self.delegate keyHit:_title];
}

Yet it is still not working. What have I missed?


Solution

  • Try this code any time you want to play system click sound in a keyboard extension:

    + (void)keyboardClickSound {
    
        // Check system preference for current setting of Keyboard Click Sound.
        CFStringRef applicationID = CFSTR("/var/mobile/Library/Preferences/com.apple.preferences.sounds");
        Boolean keyExistsAndHasValidFormat;
        BOOL enableInputClicks
        = CFPreferencesGetAppBooleanValue(CFSTR("keyboard"), applicationID, &keyExistsAndHasValidFormat);
    
        // Note: If the key does not exist because it has never been changed by a user,
        //       set it to the default, YES.
        if (!keyExistsAndHasValidFormat)
            enableInputClicks = YES;
    
        // Play Keyboard Click Sound, if enabled.
        // Note: If Open Access=Off, no click sound.
        if (enableInputClicks)
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
                       ^{ AudioServicesPlaySystemSound(1104); });
    }