AVAudioSession setCategory Swift 4.2

  • A+

After migrating to Swift 4.2, I am getting multiple errors, one of which is weird. It seems like a bug in XCode 10, but is there a workaround available?

   do {         try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, with: options)     } catch {         NSLog("Could not set audio session category")     } 

**** 'setCategory(_:with:)' is unavailable in Swift


iOS 10+

If you are targeting iOS 10+, just transition to the new API and use:

try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: []) 

Older iOS versions

When you try this for an app targeting an older Version (for example iOS 9) you will get an setCategory(_:mode:options:)' is only available on iOS 10.0 or newer Error.

This has been reported as an error and the only workaround I found was to create an Objective-C helper as described.

Here are the steps how to do it right now:

  1. Create a new Objective-C file in my case AudioSessionHelper.m. When prompted if a Bridging Header File should be created, click Yes (If you don't already have one in your project)
  2. Create a new Header file AudioSessionHelper.h
  3. Insert Code


#ifndef AudioSessionHelper_h #define AudioSessionHelper_h #import <AVFoundation/AVFoundation.h>  @interface AudioSessionHelper: NSObject + (BOOL) setAudioSessionWithError:(NSError **) error; @end  #endif /* AudioSessionHelper_h */ 


#import "AudioSessionHelper.h" #import <Foundation/Foundation.h>  @implementation AudioSessionHelper: NSObject  + (BOOL) setAudioSessionWithError:(NSError **) error {     BOOL success = [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:error];     if (!success && error) {         return false;     } else {         return true;     } } @end 
  1. Insert your helper class into Bridging Header File


#import "AudioSessionHelper.h" 
  1. Use it in your Swift project
if #available(iOS 10.0, *) {     try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: []) } else {     try AudioSessionHelper.setAudioSession() } 

This is a not beautiful and adds lots of unnecessary code and files to your project, so use it if you urgently want or must use Swift 4.2 right now. In all other cases you would be better off waiting for Apple/Swift team to fix it.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: