Created
May 7, 2016 04:32
-
-
Save jesseky/9118540350a536bce1781a4c4432c8fb to your computer and use it in GitHub Desktop.
swift http请求类
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
class KFetch { | |
let session: NSURLSession = NSURLSession.sharedSession() | |
// url安全编码 | |
func escape(str: String) -> String { | |
let characterSet = NSMutableCharacterSet.alphanumericCharacterSet() | |
characterSet.addCharactersInString("-._ ") | |
if #available(iOS 8.3, *) { | |
return str.stringByAddingPercentEncodingWithAllowedCharacters(characterSet)!.stringByReplacingOccurrencesOfString(" ", withString: "+") | |
} | |
let length = str.characters.count | |
let num = 50 | |
let times = length > (length / num * num) ? length / num + 1 : length / num | |
var result = "" | |
for i in 0 ..< times { | |
let end = i == times - 1 ? length : num * (i+1) | |
let range = (str.startIndex.advancedBy(i*num)..<str.startIndex.advancedBy(end)) | |
result += str.substringWithRange(range).stringByAddingPercentEncodingWithAllowedCharacters(characterSet)!.stringByReplacingOccurrencesOfString(" ", withString: "+") | |
} | |
return result | |
} | |
// 转换成json字符串 | |
func jsonStringify(data: NSMutableDictionary) -> (NSData?, NSError?){ | |
do { | |
let json = try NSJSONSerialization.dataWithJSONObject(data, options: NSJSONWritingOptions()) | |
return (json, nil) | |
} catch { | |
return (nil, error as NSError) | |
} | |
} | |
func jsonParseString(string: String) -> AnyObject? { | |
do { | |
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! | |
let json: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments) | |
return json | |
} catch { | |
return nil | |
} | |
} | |
func jsonParseNSData(data: NSData) -> AnyObject? { | |
do { | |
let json: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.AllowFragments) | |
return json | |
} catch { | |
return nil | |
} | |
} | |
// 请求 | |
func fetch(method: String, url: String, param: [String:String]?, headers: [String: String]?, options: [String:Bool]?, | |
callback: (body: String, headers: [String:String], error: NSError?, code: Int, time: Double) -> Void ) { | |
let pos = "POST" == method || "PUT" == method // post data or put data | |
let opt = options != nil ? (escaped: options!["escaped"] ?? false, inner: options!["inner"] ?? false) : (escaped: false, inner: false) | |
let pms = param != nil ? (opt.inner ? param!["inner"] ?? "" : param!.flatMap{"\(opt.escaped ? $0 : escape($0))=\(opt.escaped ? $0 : escape($1))"}.joinWithSeparator("&")) : "" | |
let nsu = !pos && "" != pms ? url + (url.containsString("?") ? "&" : "?") + pms : url | |
let req: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: nsu)!) | |
req.HTTPMethod = method | |
if headers != nil { // 设置头部,如果有cookie,情手动调用escape编码后再传递 | |
for (k, v) in headers! { | |
req.addValue(v, forHTTPHeaderField: k) | |
} | |
} | |
if param != nil && ("POST" == method || "PUT" == method) { // post data | |
req.HTTPBody = pms.dataUsingEncoding(NSUTF8StringEncoding) | |
} | |
let tim = CFAbsoluteTimeGetCurrent() | |
session.dataTaskWithRequest(req, completionHandler: { (body, response, error) in | |
let b: String = body != nil ? String(data: body!, encoding: NSUTF8StringEncoding)! : "" | |
let h: [String:String] = response != nil ? (response as! NSHTTPURLResponse).allHeaderFields as! [String:String] : [:] | |
let c: Int = response != nil ? (response as! NSHTTPURLResponse).statusCode : 0 | |
let t: Double = CFAbsoluteTimeGetCurrent() - tim | |
// let r = (body: b, headers: h, error: error, code: c, time: t) | |
callback(body: b, headers: h, error: error, code: c, time: t) | |
}).resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment