沉浸式体验:震动反馈

1,762 阅读1分钟

UINotificationFeedbackGenerator

typedef NS_ENUM(NSInteger, UINotificationFeedbackType) {
    UINotificationFeedbackTypeSuccess, 
    UINotificationFeedbackTypeWarning, 
    UINotificationFeedbackTypeError
};

- (void)showFeedback{
    
    UINotificationFeedbackGenerator *generator = [[UINotificationFeedbackGenerator alloc] init];
    [generator notificationOccurred:UINotificationFeedbackTypeSuccess];
}

UIImpactFeedbackGenerator

typedef NS_ENUM(NSInteger, UIImpactFeedbackStyle) {
    UIImpactFeedbackStyleLight,
    UIImpactFeedbackStyleMedium,
    UIImpactFeedbackStyleHeavy
};

- (void)showFeedback{

    UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle: UIImpactFeedbackStyleLight];
    [generator prepare];
    [generator impactOccurred];
}

UISelectionFeedbackGenerator

用来模拟选择滚轮一类控件时的震动。
- (void)showFeedback{

    UISelectionFeedbackGenerator *generator = [[UISelectionFeedbackGenerator alloc] init];
    [generator selectionChanged];
}

AudioToolbox ( iOS 10 之前 ):

播放系统音

List of SystemSoundIDs

AudioServicesPlaySystemSound (SystemSoundID);

/* --- OR --- */ 

NSURL *fileURL = [NSURL URLWithString:@"/System/Library/Audio/UISounds/ReceivedMessage.caf"]; // See List of SystemSoundIDs
SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge_retained CFURLRef)fileURL,&soundID);
AudioServicesPlaySystemSound(soundID);

播放自定义音

-(void)playSoundAfterKaoqinSuccess{
        
    NSURL *fileUrl=[[NSBundle mainBundle] URLForResource:@"kaoqin_success.caf" withExtension:nil];
    
    SystemSoundID soundID=0;
    
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
    AudioServicesAddSystemSoundCompletion(soundID, NULL, NULL, soundCompleteCallBack, NULL);
    AudioServicesPlaySystemSound(soundID);
}

void soundCompleteCallBack(SystemSoundID soundID, void * clientDate) {
    
    AudioServicesRemoveSystemSoundCompletion(soundID);
    AudioServicesDisposeSystemSoundID(soundID);
}