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

时间:2016-07-06 06:31:34

标签: ios objective-c https ssl-certificate self-signed

我有一台服务器,它使用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;
}

调用委托,trustResult等同于kSecTrustResultUnspecified(表示“受信任,没有明确的用户覆盖”),如预期的那样。但是,使用以下AVPlayerItem.error

后不久播放失败
  

错误Domain = NSURLErrorDomain Code = -1200“发生SSL错误,无法与服务器建立安全连接。” UserInfo = {NSLocalizedRecoverySuggestion =您是否要连接到服务器?,NSUnderlyingError = 0x16c35720 {错误域= NSOSStatusErrorDomain代码= -1200“(null)”},NSLocalizedDescription =发生SSL错误并且与服务器的安全连接无法做成。}

如何让AVPlayer接受SSL握手?

1 个答案:

答案 0 :(得分: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;
}

然而,由于我还没有辨别出来,从iOS 10.0.1起停止工作。所以这可能对您有所帮助,也可能没有帮助。祝你好运!