swift使用cookie

//
//  ViewController.swift
//  加密
//
//  Created by admin on 16/2/27.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    // 发送下请求,服务器那边有写cookie的代码
    @IBAction func sendRequest(sender: AnyObject) {
        let url = NSURL(string: "http://test.com/login2.php")
        let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringCacheData, timeoutInterval: 10)
        let postData = "username=zhangsan&password=zhang"
        request.HTTPMethod = "post"
//        request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
        // 请求会自动带上cookie
        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (response:NSURLResponse?, data:NSData?, error:NSError?) -> Void in
            print(try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments))
        }
    }
    @IBAction func readCookie(sender: AnyObject) {
        // 第一次读取是没有任何输出的,发送请求之后久能取到下面的值了,因为服务器设置了cookie
        for cookie in NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
        {
            if(cookie.name == "userName")
            {
                print("用户名为\(cookie.value)")
            }
            if(cookie.name == "userPassword")
            {
                print("密码为\(cookie.value)")
            }
        }
    }
}

标签: swift, 网络

添加新评论