如何使用带有HTTPS和自签名服务器证书的AVPlayer?

Nic*_*rge 8 https objective-c self-signed ssl-certificate ios

我有一台服务器使用HTTPS的自签名SSL证书.我将自签名的root证书捆绑到我的应用程序中.我可以NSURLSession通过SecTrustSetAnchorCertificates()-URLSession:didReceiveChallenge:completionHandler:委托方法中使用来使用和验证自签名根证书.

AVPlayer但是,当我尝试使用时,我收到SSL错误并且播放失败.这是我的AVAssetResourceLoader委托实施:

- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader shouldWaitForResponseToAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge.protectionSpace.authenticationMethod isEqual:NSURLAuthenticationMethodServerTrust]) {
        SecTrustRef trust = challenge.protectionSpace.serverTrust;
        SecTrustSetAnchorCertificates(trust, (__bridge CFArrayRef)self.secTrustCertificates);

        SecTrustResultType trustResult = kSecTrustResultInvalid;
        OSStatus status = SecTrustEvaluate(trust, &trustResult);

        if (status == errSecSuccess && (trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed)) {
            [challenge.sender useCredential:[NSURLCredential credentialForTrust:trust] forAuthenticationChallenge:challenge];
            return YES;
        } else {
            [challenge.sender cancelAuthenticationChallenge:challenge];
            return YES;
        }
    }
    return NO;
}
Run Code Online (Sandbox Code Playgroud)

委托被调用,并且trustResult等同于kSecTrustResultUnspecified(这意味着"受信任,没有明确的用户覆盖"),如预期的那样.但是,播放失败后不久,具有以下内容AVPlayerItem.error:

错误域= NSURLErrorDomain代码= -1200"发生SSL错误,无法与服务器建立安全连接." 的UserInfo = {NSLocalizedRecoverySuggestion =你想连接到服务器反正?NSUnderlyingError = {0x16c35720误差区域= NSOSStatusErrorDomain代码= -1200"(空)"},NSLocalizedDescription =发生了SSL错误和服务器的安全连接不能做成.}

我怎样才能AVPlayer接受SSL握手?

T'P*_*Pol 3

这个实现对我有用:

- (BOOL)resourceLoader:(AVAssetResourceLoader *)resourceLoader
shouldWaitForResponseToAuthenticationChallenge:(NSURLAuthenticationChallenge *)authenticationChallenge
{
    //server trust
    NSURLProtectionSpace *protectionSpace = authenticationChallenge.protectionSpace;
    if ([protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        [authenticationChallenge.sender useCredential:[NSURLCredential credentialForTrust:authenticationChallenge.protectionSpace.serverTrust] forAuthenticationChallenge:authenticationChallenge];
        [authenticationChallenge.sender continueWithoutCredentialForAuthenticationChallenge:authenticationChallenge];
    }
    else { // other type: username password, client trust...
    }
    return YES;
}
Run Code Online (Sandbox Code Playgroud)

然而,从 iOS 10.0.1 开始,它就停止工作了,原因我还不清楚。所以这可能对你有帮助,也可能没有帮助。祝你好运!