[iOS] 不合法的伺服器憑證問題
這是個很奇妙的議題,明明是用去年人家寫的案子呼叫API的程式碼,連第三方套件也一模一樣,所帶入的方法和參數一模一樣,但是卻跑不出相同的結果⋯⋯
不知怎麼命名這篇文章,暫且以不合法的伺服器憑證問題為名吧!似乎跟http和https有關聯?還有什麼SSL?
然後就跑出這幾行訊息:
The certificate for this server is invalid. You might be connecting to a server that is pretending to be “xxx.ooo.com.tw” which could put your confidential information at risk.
查了網路前人的解法,原來只要在兩個delegate改成這樣⋯⋯
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace { return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]; } - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; }
起初還想要請負責server端的人改安全性程度,不過既然去年的project都可以成功跑出結果,還是由我app端來處理問題吧!
寫了以上的code,還是不太明白意義⋯⋯知道的人請跟我說一下><;
參考:How to use NSURLConnection to connect with SSL for an untrusted cert?、NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813) iOS。
HappyMan・迴響