1、swift带报文的网络请求
static func request_object(method:String,url:String,bodyStr:NSString,callback:(data:NSData!,resopnse:NSURLResponse!,error:NSError!)->Void){ let session = NSURLSession.sharedSession(); let request = NSMutableURLRequest(URL: NSURL(string: url)!); request.HTTPMethod = method; request.HTTPBody = bodyStr.dataUsingEncoding(NSUTF8StringEncoding); let task = session.dataTaskWithRequest(request,completionHandler: {(data,response,error) -> Void in callback(data: data,resopnse: response,error: error); } ) task.resume(); }
static func request_news_info(Params:Array<AnyObject>,error:NSError!)->Void){ var params_dictionary = Dictionary<String,AnyObject>(); params_dictionary["Token"] = token; params_dictionary["Task"] = "1"; params_dictionary["Module"] = "7"; params_dictionary["Params"] = Params; do{ let data = try NSJSONSerialization.dataWithJSONObject(params_dictionary,options: NSJSONWritingOptions.PrettyPrinted) let strJson=NSString(data: data,encoding: NSUTF8StringEncoding) NetWork.request_object("POST",url: request_url,bodyStr: strJson!) { (data,resopnse,error) -> Void in callback(data: data,resopnse: resopnse,error: error) } }catch{ print("Error"); callback(data: nil,resopnse: nil,error: nil) } }
let array = Array<AnyObject>(); RequestData.request_news_info(array,callback: { (data,error) -> Void in let string = NSString.init(data:data,encoding:NSUTF8StringEncoding); print(string); })
搞了4个小时,由于我看不太懂oc的方法,百度基本没找到,猜了半天写了这么点,本来我想直接传NSData类型,但是我始终不晓得怎么初始化NSData,并传值进去
求大神