httpPost
import Foundation
//网络请求类
class HttpRequest: NSObject{
override init() {
super.init()
}
class func parseJSONData(data: AnyObject?) ->NSArray?{
do{
let downloadData=data as? NSData
let jsonObject = try NSJSONSerialization.JSONObjectWithData(downloadData!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
return jsonObject
}catch{
}
return nil
}
class func post(urlString urlString: String?,postParams: NSDictionary!,completion: (data: NSArray?) -> Void){
if urlString == nil {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print("urlString 为空")
completion(data: nil)
})
}
let url = NSURL(string: urlString!)
let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 10)
request.HTTPMethod = "POST"
parseParams(Params: postParams, completion: {(result) in
let postData: NSData = (result?.dataUsingEncoding(NSUTF8StringEncoding))!
request.HTTPBody = postData
})
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler: {
(response,data,error) -> Void in
let httpResponse = response as? NSHTTPURLResponse
if httpResponse?.statusCode == 200{
let parseData = self.parseJSONData(data)
dispatch_async(dispatch_get_main_queue(),{
() -> Void in
completion(data: parseData)
})
}else {
dispatch_async(dispatch_get_main_queue(), {
() -> Void in
print(error)
completion(data: nil)
})
}
})
}
class func request(urlString urlString: String?,completion: (data: NSArray?) -> Void){
if urlString == nil {
dispatch_async(dispatch_get_main_queue(),{ () -> Void in
print("urlString 为空")
completion(data: nil)
})
}
let url = NSURL(string: urlString!)
let request = NSURLRequest(URL: url!)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue) {
(response, data, error) -> Void in
let httpResponse = response as? NSHTTPURLResponse
let code=httpResponse?.statusCode
if code==200{
let parseData = self.parseJSONData(data)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completion(data: parseData)
})
}else{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
print(error)
// 请求出现,则返回nil对象表示
completion(data: nil)
})
}
}
}
class func parseParams(Params Params: NSDictionary!,completion: (paramString: NSString?) -> Void){
var keyValueFormat: String?
let result = NSMutableString()
let keyEnum = Params.keyEnumerator()
while let key = keyEnum.nextObject() as? String{
keyValueFormat = String.init(format: "%@=%@&", arguments: [key,(Params.valueForKey(key)?.description)!])
result.appendString(keyValueFormat!)
}
completion(paramString: result)
}
}
使用:
let dc=NSDictionnary(object:a,forKeys:b)
HttpRequest.post(urlString:"http://59.78.93.208:9097//AdviseInsert",postParam:dc,completion:{_ in})