如何使用iOS Swift在REST Web服务URL上应用Cookie

时间:2015-06-15 08:00:54

标签: ios iphone swift cookies

我已经从我的应用程序发出了一个REST请求,我能够正确地获取数据。现在我想在此Web服务URL上应用身份验证cookie。我们应该怎么做。请帮忙。以下是我目前的代码。

CallRestParser.swift - 在此processRequest方法将从某个视图控制器调用。 processRequest方法将接收Web服务URL并向RESTParser类发送请求。 getReceiveData是一个委托方法,将在成功连接后调用。

protocol UpdateProjectUIDelegate{
    func UpdateProjectUI(data:NSDictionary)
}
class CallRESTParser: NSObject, RESTParserDelegate {
    var rest1=RESTParser()
    var projectDelegate: UpdateProjectUIDelegate?
    func processRequest(url:String) {
        var nsURL = NSURL(string: url)
        var createrequest: NSMutableURLRequest = NSMutableURLRequest(URL: nsURL!)
        createrequest.HTTPMethod = "GET"
        rest1.delegate = self
        rest1.httpRequest(createrequest)

    }

    func getReceiveData(recvData:NSMutableData,sender:RESTParser){
        var error: NSError?

        var jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(recvData, options:NSJSONReadingOptions.MutableContainers, error: &error) as? NSDictionary

        if error != nil{
            print("Error occured  \(error?.localizedFailureReason)")
            return
        }
        println(jsonResult.count)
        projectDelegate?.UpdateProjectUI(jsonResult)
        //var updateUI = ProjectDetails_tab()
        //updateUI.updateUI()


    }
}

RESTParser.swift -

protocol RESTParserDelegate{
    func getReceiveData(data:NSMutableData,sender:RESTParser)
}


class RESTParser: NSObject, NSURLConnectionDataDelegate {

    var receiveData: NSMutableData!
    var requestConnection: NSURLConnection!
    var delegate: RESTParserDelegate?

    func receiveData(resData:NSMutableData){
        receiveData = resData
    }

    func requestConnection(reqConn:NSURLConnection){
        requestConnection = reqConn
    }

    func httpRequest(myRequest:NSMutableURLRequest){
        self.requestConnection = NSURLConnection(request: myRequest, delegate: self)

    }
    // NSURLConnectionDataDelegate methods
    func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse){
        self.receiveData = NSMutableData()

    }

    func connection(connection: NSURLConnection, didReceiveData data: NSData){
        self.receiveData.appendData(data)
    }

    func connectionDidFinishLoading(connection: NSURLConnection){
        //if let revData = receiveData{
        self.delegate?.getReceiveData(receiveData, sender: self)
        //}else
        //{
          //  NSLog("No data : nil")
        //}
        self.delegate = nil
        self.receiveData = nil
        self.requestConnection = nil
    }
    func connection(connection: NSURLConnection, didFailWithError error: NSError){
        NSLog("Failed with error - %@ ",error.localizedDescription)

    }
    func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool{
        return protectionSpace.authenticationMethod  == NSURLAuthenticationMethodServerTrust
    }
    func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge){
        if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust){
            if(challenge.protectionSpace.host == "domain.com"){
                let credentials = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
                challenge.sender.useCredential(credentials, forAuthenticationChallenge: challenge)
            }
        }
        challenge.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)

    }
}

我们从authSessionCookieKeyVal获得的身份验证Cookie是这样的 - XX-X-SESSION-ID = 1_2_1_XXxXXXgSaG1K5aXXXXXXXV。如何在上述REST调用中应用此cookie。请帮忙。

1 个答案:

答案 0 :(得分:0)

您必须在header

NSMutableURLRequest内传递Cookie
    var nsURL = NSURL(string: url)
    var createrequest: NSMutableURLRequest = NSMutableURLRequest(URL: nsURL!)

    let cookieArray = NSArray(objects: Cookie1,Cookie2) // Cookie1 and Cookie2 is an object of NSHTTPCookie
    let cookieHeader = NSHTTPCookie.requestHeaderFieldsWithCookies(cookieArray)
    createrequest.allHTTPHeaderFields = NSDictionary(dictionary: cookieHeader)

修改

Cookie存储在NSHTTPCookieStorage

    var Cookie1:NSHTTPCookie?  // Cookie Object
    var Cookie2:NSHTTPCookie? // Cookie Object
    let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
    let cookieArray = storage.cookies!

    for tempCookie in cookieArray
    {
        if tempCookie.name == "rtFa" // Write your cookie name which you want to search
        {
            Cookie1 = tempCookie as? NSHTTPCookie
            continue
        }
        else if tempCookie.name == "FedAuth" // Write your cookie name which you want to search
        {
            Cookie2 = tempCookie as? NSHTTPCookie
            continue
        }
    }

    if Cookie1 != nil && Cookie2 != nil
    {
        println("Cookie Found")
    }
    else
    {
        println("Cookie Not Found")
    }