Dee*_*rma 16 xcode avaudiosession swift xcode10 swift4.2
迁移到Swift 4.2后,我遇到了多个错误,其中一个很奇怪.这似乎是Xcode 10中的一个错误,但有没有可用的解决方法?
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord, with: options)
} catch {
NSLog("Could not set audio session category")
}
Run Code Online (Sandbox Code Playgroud)
****'setCategory(_:with :)'在Swift中不可用
小智 31
如果您的目标是iOS 10+,只需转换到新的API并使用:
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [])
Run Code Online (Sandbox Code Playgroud)
当您针对较旧版本(例如iOS 9)的应用尝试此操作时,您将收到setCategory(_:mode:options:)' is only available on iOS 10.0 or newer错误消息.
这已被报告为Apples API中的错误.在等待修复时,我找到了一种解决方法.当您按照描述创建Objective-C帮助程序时,您仍然可以访问旧API,因为它仍然针对Objective-C公开.
如果您想在没有错误处理的情况下进行快速内联修复,可以使用以下.perform()方法调用Obj.-C API :
if #available(iOS 10.0, *) {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
} else {
// Set category with options (iOS 9+) setCategory(_:options:)
AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:withOptions:error:"), with: AVAudioSession.Category.playback, with: [])
// Set category without options (<= iOS 9) setCategory(_:)
AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:error:"), with: AVAudioSession.Category.playback)
}
Run Code Online (Sandbox Code Playgroud)
如果您想要更多地控制错误,以下是如何立即执行此操作的步骤
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 /* AudioSessionHelper_h */
Run Code Online (Sandbox Code Playgroud)
AudioSessionHelper.m
#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
Run Code Online (Sandbox Code Playgroud)
#import "AudioSessionHelper.h"
Run Code Online (Sandbox Code Playgroud)
if #available(iOS 10.0, *) {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
} else {
try AudioSessionHelper.setAudioSession()
}
Run Code Online (Sandbox Code Playgroud)
这不是很漂亮,并且会为您的项目添加许多不必要的代码和文件,因此如果您迫切需要或必须立即使用Swift 4.2,请使用它.在所有其他情况下,您最好等待Apple/Swift团队修复它.
| 归档时间: |
|
| 查看次数: |
6569 次 |
| 最近记录: |