首页 > 代码库 > 熟练使用Alamofire请求数据

熟练使用Alamofire请求数据

如果项目稍大一些,就尽量使用路由Route 组织形成url请求,避免很多次重复代码, 看起来也直观.

import UIKitimport Alamofirestruct KF {enum Router: URLRequestConvertible{    static let baseUrlString = "http://www.aaazb.com"        case login([String: AnyObject])        var  method : Alamofire.Method{        switch self{        case .login:            return .POST        }    }        var path: String{        switch self{        case .login:            return "/login"        }    }        var URLRequest: NSURLRequest{        let URL = NSURL(string: Router.baseUrlString)        let mutableURLRequest = NSMutableURLRequest(URL:URL!.URLByAppendingPathComponent(path))            mutableURLRequest.HTTPMethod = method.rawValue        mutableURLRequest.setValue("secondzilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) ipad/40.0.2125.122 Safari/537.36", forHTTPHeaderField: "User-Agent")        mutableURLRequest.setValue("XMLHttpRequest", forHTTPHeaderField: "X-Request-With")        mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Accept")        switch self{        case .login(let parameters):             return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0        }    }}}

用到请求的时候:

Alamofire.request(KindFoo.Router.login(["user_name":"shan","user_pwd":"shan","uuid":"567-F8E9EBC8-6286-420A-B9D8-9FABC50B30CD"]))            .responseJSON { (_, _, JSON, _) in            println(JSON!.valueForKey("m"))            //println(JSON)        }

Alamofire是基于NSURLRequest封装的,所以Cookie会自动保存,就和浏览器请求是一个效果,而且网站Set_cookie多久,本地的Cookie 就多久,每次请求的时候都会自动带上cookie,直到过期.

如何查看cookie:

var url = NSURL(string: "http://www.aaazb.com")var cookieJar = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(url!)

如何清空Cookie:

 var url = NSURL(string: "http://www.aaazb.com") var cookieJar:NSArray = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookiesForURL(url!)! //print(cookieJar.count) for i in cookieJar {    NSHTTPCookieStorage.sharedHTTPCookieStorage().deleteCookie(i as NSHTTPCookie) }

设置Cookie:

 

熟练使用Alamofire请求数据