iOS 10+
如果你的目标是,那么只需过渡到新的API并使用:
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [])
旧版iOS
当您尝试针对一个旧版本的iOS(例如iOS 9)的应用程序进行此操作时,将会出现setCategory(_:mode:options:)'仅在iOS 10.0或更高版本上可用
错误。
这已被报告为Apple API中的错误并在Xcode 10.2中得到修复。对于旧版本的Xcode(例如Xcode 10.1),我发现有一种解决方法。当您创建一个Objective-C帮助程序时,因为该API仍然是Objective-C的公开接口,因此仍然可以访问旧的API。
解决方法1:.perform()方法
如果您想要一个快速的内联修复而无需错误处理,可以使用.perform()
方法调用Obj.-C API:
if #available(iOS 10.0, *) {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
} else {
AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:withOptions:error:"), with: AVAudioSession.Category.playback, with: [])
AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:error:"), with: AVAudioSession.Category.playback)
}
解决方法2:帮助类方法
如果你想对错误有更多的控制,下面是如何立即实现的步骤:
- 创建一个新的
Objective-C
文件,在我的情况下是AudioSessionHelper.m
。如果提示是否应该创建桥接头文件,请单击是(如果您的项目中没有这个文件)。
- 创建一个新的
Header
文件AudioSessionHelper.h
- 插入代码
#ifndef AudioSessionHelper_h
#define AudioSessionHelper_h
#import <AVFoundation/AVFoundation.h>
@interface AudioSessionHelper: NSObject
+ (BOOL) setAudioSessionWithError:(NSError **) error;
@end
#endif
#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
- 将你的辅助类插入到桥接头文件中
- 在你的Swift项目中使用它
if #available(iOS 10.0, *) {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
} else {
try AudioSessionHelper.setAudioSession()
}
这种方法不美观,会给你的项目添加大量不必要的代码和文件,因此如果你现在急需或必须使用Swift 4.2在Xcode 10.1上,请使用它。在所有其他情况下,最好使用Xcode 10.2。