2015-01-13 1 views
4

저는 비교적 IOS 개발에 익숙하지 않습니다. 그러니 나와 함께 견뎌내고 아무것도 아닌 것을 용서해주세요!Swift에서 유효한 SSL 인증서와 함께 NSURLConnection 사용하기

NSURLConnection을 사용하여 SOAP 웹 서비스에서 데이터를 다시 가져 오려고하는데 정상적으로 작동합니다.

그러나 http에서 https로 URL을 변경하면 더 이상 데이터가 반환되지 않으며 기대했던 것과 같은 오류가 발생하지 않습니다.

https 인증서는 godaddy의 올바른 인증서이며 정상적으로 모든 브라우저 등에서 정상적으로 볼 수 있습니다. 기본적으로 아무도 http에서 https로 변경하면 아무런 문제가 발생하지 않습니다. ...

코드 스위프트이며 다음과 같다 :

// Create the SOAP Message to send 
    var soapMessage = "<?xml version='1.0' encoding='UTF-8'?><SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/' xmlns:ns1='http://tempuri.org/'><SOAP-ENV:Body><ns1:get_Test/></SOAP-ENV:Body></SOAP-ENV:Envelope>" 

    NSLog("soapMessage generated is: %@", soapMessage) 

    // Soap URL Works 
    var urlString = "http://api.domain.com/testservice.svc" 

    //Below https URL does not work 
    //var urlString = "https://api.domain.com/testservice.svc" 

    var url = NSURL(string: urlString) 
    var theRequest = NSMutableURLRequest(URL: url!) 

    //Get Length of request 
    var msgLength = String(countElements(soapMessage)) 

    // POST Header values 
    theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type") 
    theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length") 
    theRequest.addValue("http://tempuri.org/IService/get_Test", forHTTPHeaderField: "SoapAction") 
    theRequest.HTTPMethod = "POST" 
    theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) 
    NSLog("Request is: %@", theRequest.allHTTPHeaderFields!) 

    var connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true) 
    connection?.start() 

    if (connection == true) { 
     var mutableData : Void = NSMutableData.initialize() 
    } 

또있는 NSURLConnection 코드이다

// NSURLConnectionDelegate 
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { 
    mutableData.length = 0; 
} 

func connection(connection: NSURLConnection!, didReceiveData data: NSData!) { 
    mutableData.appendData(data) 
} 


func connection(connection: NSURLConnection, didFailWithError error: NSError) { 
    NSLog("Error with Soap call: %@", error) 
} 

func connectionDidFinishLoading(connection: NSURLConnection!) { 
    var xmlParser = NSXMLParser(data: mutableData) 
    xmlParser.delegate = self 
    xmlParser.parse() 
    xmlParser.shouldResolveExternalEntities = true 
} 
// NSURLConnectionDelegate 

그럼 헥타르 DoStartElement, didEndElement, foundCharacters, parserDidEndDocument 등등과 같은 파서 물건.

다음과 같이 NSURLConnection의 대리인을 추가했지만 아무 것도 변경되지 않았습니다. 로깅이 나타나면 호출됩니다. 이 코드를 통해 실행

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace?) -> Bool 
{ 
    NSLog("am here") 
    return protectionSpace?.authenticationMethod == NSURLAuthenticationMethodServerTrust 
} 

func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge?) 
{ 
    NSLog("am here 2") 
    if challenge?.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust 
    { 
     if challenge?.protectionSpace.host == "api.domain.com" 
     { 
      NSLog("yep") 
      let credentials = NSURLCredential(forTrust: challenge!.protectionSpace.serverTrust) 
      challenge!.sender.useCredential(credentials, forAuthenticationChallenge: challenge!) 
     } 
    } 
    challenge?.sender.continueWithoutCredentialForAuthenticationChallenge(challenge!) 
} 

는에 도달은 "네"그래서 나는 인증서를 신뢰해야 이해하지만, 내가 HTTPS URL을 사용할 때 여전히 아무것도 표시되지 않습니다 것과.

https와 다른 코드와 차이가 없으며 인증서가 올바로 유효하므로 http가 아닌 https를 사용하여 데이터를 다시 가져 오는 방법은 무엇입니까?

많은 경우 고마워요. 그리고 이것이 바보 같은 질문이라면 죄송합니다.

데이브

추가 :

var connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: false) 
    connection?.start() 

    if (connection == true) { 
     var mutableData : Void = NSMutableData.initialize() 
    } else { 
     NSLog("Error with connection, details: %@", connection!) 
    } 

그래서이 지금은 SSL을 실행하면 "오류 연결"로그 : 나는 지금 연결을 변경 한 확인

!

그래서 그때에 didreceiveresponse을 변경 한 :

func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) { 
    mutableData.length = 0; 
    var httpresponse = response as? NSHTTPURLResponse 
    println("status \(httpresponse?.statusCode)") 
    println("headers \(httpresponse?.allHeaderFields)") 
} 

내가 다시 상태 코드가 404임을 알 - 난 그냥 웹 서비스가 분명히 존재로 이해하지 않고, 사용 구문 분석 할 수있는 온라인 파서!

그래도 여전히 붙어 있지만 적어도 문제를 지적하고 있습니다. 누구든지 나를 도울 생각이 있습니까? 그래서 위의 SWIFT 코드는 이제 잘 작동

 <bindings> 
     <basicHttpBinding> 
      <binding> 
       <security mode="Transport"> 
        <transport clientCredentialType="None"/> 
       </security> 
      </binding> 
     </basicHttpBinding> 
    </bindings> 
    <services> 
     <service name="Service.Service"> 
      <endpoint address="" binding="basicHttpBinding" contract="Service.IService" /> 
     </service> 
    </services> 

이 그것을 고정 :

사람이 다른이에 걸리면
+1

모든 질문이 귀하의 것으로 명시되기를 바랍니다. 그러나 미안하지만 나는 그 해답을 모른다. 오류 메시지가 나타 납니까? 당신이 말할 수있는 서버로부터의 응답? –

+0

오류가 있습니까? 아니면 성공적인 응답을 받고 응답 객체가 비어 있습니까? – tng

+0

의견에 감사드립니다. 어떤 종류의 오류도 발생하지 않습니다. 이 코드는 NSURLConnectionDelegate에 들어 가지 않습니다. didFailWithError 나 didCancelAuthenticationChallenge를 치지 않습니다. (! forTrust : 도전 .protectionSpace.serverTrust) 자격 증명 = NSURLCredential 보자 : 그것은 단지 didReceiveAuthenticationChallenge 및 실행이 다네! 도전을 .sender.useCredential (자격 증명을 forAuthenticationChallenge! 도전) 다음 단지 더 이상 처리를 중지! 그러나 SSL을 제거하고 모든 것이 잘 작동합니다. – Dave

답변

1

는 다음 SVC 웹 서비스에 대한 웹 설정이 변경되었습니다! 거친 하나 인 휴!

관련 문제