网上有很多Cookie读写的代码
我自己整理了一份:
CookiesUtils.swift
// //用于保存网页登陆的cookie信息,实现二次登陆面登陆的功能,同时获取cookie中的用户信息保存到本地 // manyiwang // // Created by weichongchong on 16/10/14. // Copyright © 2016年 manyiwang. All rights reserved. // import UIKit class CookiesUtils { //保存登录后网页的cookie信息 static func saveCookies() { //print("保存cookie信息:"); if let cookies: NSArray = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(NSURL(string: MyConstant.ArtWork_WebUrl)!)! { let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(cookies) NSUserDefaults.standardUserDefaults().setObject(data,forKey: "manyiabycookie") //将用户名保存到本地 //var userDefault = NSUserDefaults.standardUserDefaults() // userDefault.setObject("15539187816",forKey: "username") // var nsStringValue = userDefault.objectForKey("username") as! NSString }else{ print("保存cookie信息失败") } } //把保存的cookie信息取出来,在下次登陆的时候设置进去实现面登陆 static func retrieveCookies() { //print("取出保存到本地的cookie信息:") let cookiesdata:NSData! = NSUserDefaults.standardUserDefaults().objectForKey("manyiabycookie") as? NSData if(cookiesdata == nil ){ print("取出保存到本地的cookie信息:cookiesdata == nil ") }else{ // print("取出保存到本地的cookie信息:") if cookiesdata.length > 0{ let cookies: NSArray = NSKeyedUnarchiver.unarchiveObjectWithData(cookiesdata) as! NSArray for cookie in cookies { NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie as! NSHTTPCookie) print(cookie.name) if(cookie.name == "userName"){ print(cookie.name) //print(String(cookie.values))//这句代码返回为空nil //获取用户名 let usernameString:String = String(cookie.valueForKey("value")) //字符串截取需要的信息 let range=Range<String.Index>(start: usernameString.startIndex.advancedBy(9),end: usernameString.endIndex.advancedBy(-1)) //Swift 2.0 let userName=usernameString.substringWithRange(range) // print(usernameString) // print(userName) //将用户名保存到本地 var userDefault = NSUserDefaults.standardUserDefaults() userDefault.setObject(userName,forKey: "username") } } //打印全部的name和value //var name:String = String(cookies.valueForKey("name")) // var value:String = String(cookies.valueForKey("value")) // print(name) // print(cookies.valueForKey("value")) //print(cookiesdata) } } } }原文链接:https://www.f2er.com/swift/322819.html