2015-06-09 86 views
4

我一直在使用HTTP進行開發。下面的代碼在使用HTTP與開發服務器連接時效果很好。但是,當我將方案更改爲https時,它不會將成功的https帖子發送到服務器。如何使用NSURLSession在swift中發送HTTPS POST請求

我還需要做什麼才能從HTTP POST切換到HTTPS POST?

class func loginRemote(successHandler:()->(), errorHandler:(String)->()) { 

    let user = User.sharedInstance 

    // this is where I've been changing the scheme to https 
    url = NSURL(String: "http://url.to/login.page") 

    let request = NSMutableURLRequest(URL: url) 

    let bodyData = "email=\(user.email)&password=\(user.password)" 
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding); 

    request.HTTPMethod = "POST" 

    let session = NSURLSession.sharedSession() 

    // posting login request 
    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in 
     if let httpResponse = response as? NSHTTPURLResponse { 
      if httpResponse.statusCode == 200 { 
       // email+password were good 

       successHandler()      

      } else { 
       // email+password were bad 
       errorHandler("Status: \(httpResponse.statusCode) and Response: \(httpResponse)") 
      } 
     } else { 
      NSLog("Unwrapping NSHTTPResponse failed") 
     } 
    }) 

    task.resume() 
} 

回答

2

您將必須實施NSURLSessionDelegate方法之一,以便它將接受SSL證書。

class YourClass: Superclass, NSURLSessionDelegate { 

    class func loginRemote(successHandler:()->(), errorHandler:(String)->()) { 
     // ... 
     let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), 
            delegate: self, 
            delegateQueue: nil) 
     // ... 
    } 

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { 
     if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { 
      let credential = NSURLCredential(trust: challenge.protectionSpace.serverTrust) 
      completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential) 
     } 
    } 

} 

警告:這會盲目地接受您嘗試的任何SSL證書/連接。這不是一種安全的做法,但它可以讓你使用HTTPS測試你的服務器。