Xcode自动生成MyProject-Swift.h文件编译报错,如何解决?
问题场景
编译时错误出现在Xcode自动生成的MyProject-swift.h文件中,该文件的Objective-C代码如下:
SWIFT_CLASS("_TtC3sfw17ContentKeyManager") @interface ContentKeyManager : NSObject <AVContentKeySessionDelegate> - (void)contentKeySession:(AVContentKeySession * _Nonnull)session didProvideContentKeyRequest:(AVContentKeyRequest * _Nonnull)keyRequest; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end
出现三个编译错误:
Type argument 'AVContentKeySession' must be a pointer (requires a '*')
Insert ' *'
Type arguments cannot be applied to non-parameterized class 'NSObject'
Remove ''
Unknown class name 'AVContentKeySessionDelegate'; did you mean 'AVContentKeySession'?
Replace 'AVContentKeySessionDelegate' with 'AVContentKeySession'
对应的Swift代码:
import Foundation import AVFoundation class ContentKeyManager: NSObject, AVContentKeySessionDelegate {
当前环境:Xcode 14.0.1、Swift 5
解决方法
这些错误本质是Objective-C无法识别Swift桥接文件中的AVFoundation协议类型,核心原因是桥接文件未引入AVFoundation头文件,导致编译器找不到AVContentKeySessionDelegate的定义,按以下步骤解决:
显式引入AVFoundation头文件
如果项目有自定义桥接文件(如MyProject-Bridging-Header.h),在其中添加:#import <AVFoundation/AVFoundation.h>若没有自定义桥接文件,直接在引用
MyProject-swift.h的Objective-C文件头部添加上述导入语句。修正Swift类的访问权限
默认的internal访问权限可能导致桥接文件生成不完整,将ContentKeyManager改为public或open权限:import Foundation import AVFoundation public class ContentKeyManager: NSObject, AVContentKeySessionDelegate { // 实现协议所需方法 }清理并重新编译
执行Product > Clean Build Folder(快捷键Shift+Command+K),重启Xcode后重新编译项目。
以上操作可让编译器正确识别AVFoundation的协议与类型,解决全部报错。
内容的提问来源于stack exchange,提问作者Александр Уткин

