vje1998
vje1998

Reputation: 691

How to play notification sound when app goes in background?

-(void)loadAudioFileList
{
   audioFileList = [[NSMutableArray alloc] init];
   arrAudioList  = [[NSMutableArray alloc] init];

   NSFileManager *fileManager = [[NSFileManager alloc] init];
   NSURL *directoryURL = [NSURL URLWithString:@"/System/Library/Audio/UISounds"];
   NSArray *keys = [NSArray arrayWithObject:NSURLIsDirectoryKey];

   NSDirectoryEnumerator *enumerator = [fileManager
                                     enumeratorAtURL:directoryURL
                                     includingPropertiesForKeys:keys
                                     options:0
                                     errorHandler:^(NSURL *url, NSError *error) {
                                         // Handle the error.
                                         // Return YES if the enumeration should continue after the error.
                                         return YES;
                                     }];

   for (NSURL *url in enumerator)
   {
       NSError *error;
       NSNumber *isDirectory = nil;
       if (! [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:&error])
       {
          // handle error
       }
       else if (! [isDirectory boolValue])
       {
          [audioFileList addObject:url];
          [arrAudioList addObject:[url lastPathComponent]];
       }
   }
}

I fetch the system audio files available using above code. i m able to play notification sound when app is in foreground using below code.

SystemSoundID soundID;
AudioServicesCreateSystemSoundID((__bridge_retained   CFURLRef)fileURL,&soundID);
AudioServicesPlaySystemSound(soundID);

but if app is in background i m not able to play sound. i google for the solution but i didn't find any. As i know if we have included sound files to our app bundle we are able to play notification sound even if app is in background but with system sounds we are not able to achieve the same. Any help will be appreciated.

Upvotes: 1

Views: 516

Answers (1)

Dattatray Deokar
Dattatray Deokar

Reputation: 2103

You need to enable background Mode with Audio Service enabled. like shown in below screenshotenter image description here

Upvotes: 1

Related Questions