Подтвердить что ты не робот

Как Spotify настраивает элементы управления воспроизведением мультимедиа в iOS?

Spotify на iOS имеет очень интересную интеграцию Центра управления. Обратите внимание на кнопку гамбургера ниже.

Hamburger

То же самое происходит на экране блокировки!

lock screen

Как они это делают? Есть ли API в MPMediaCenter или что-то в этом роде?

4b9b3361

Ответ 1

Да, для этого есть API для

Изучая инструкции, содержащиеся в яблочных документах относительно событий дистанционного управления, вы выделяете два класса MPRemoteCommand и MPRemoteCommandCenter. Глядя на MPRemoteCommandCenter, вы увидите, что существует множество команд, таких как likeCommand или dislikeCommand, для которых вы можете добавить обработчики. Добавление обработчиков к этим командам приводит к тому, что они отображаются в центре управления.

Ниже приведен код "все-в-одном", который почти полностью соответствует тем же результатам, что и на ваших снимках экрана:

- (void)showCustomizedControlCenter {
    /* basic audio initialization */
    NSString *soundFilePath = [NSString stringWithFormat:@"%@/test.mp3", [[NSBundle mainBundle] resourcePath]];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];

    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
    self.player.numberOfLoops = -1;
    [self.player play];

    /* registering as global audio playback */
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

    /* the cool control center registration */
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    [commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent *event) {
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    [commandCenter.dislikeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent *event) {
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    [commandCenter.likeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent *event) {
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent *event) {
        return MPRemoteCommandHandlerStatusSuccess;
    }];

    /* setting the track title, album title and button texts to match the screenshot */ 
    commandCenter.likeCommand.localizedTitle = @"Thumb Up";
    commandCenter.dislikeCommand.localizedTitle = @"Thumb down";

    MPNowPlayingInfoCenter* info = [MPNowPlayingInfoCenter defaultCenter];
    NSMutableDictionary* newInfo = [NSMutableDictionary dictionary];

    [newInfo setObject:@"Mixtape" forKey:MPMediaItemPropertyTitle];
    [newInfo setObject:@"Jamie Cullum" forKey:MPMediaItemPropertyArtist];

    info.nowPlayingInfo = newInfo;
}

В дополнение к написанию кода вам нужно

  • добавить AVFoundation в свой проект
  • #import <AVFoundation/AVFoundation.h> и #import <MediaPlayer/MediaPlayer.h>
  • активировать фоновый режим "Audio and AirPlay" в настройках приложения.

enter image description hereenter image description here