同步操作将从 腾讯开源/APIJSON 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
//// ViewController.swift// testswift//// Created by TommyLemon on 17/11/28.// Copyright © 2017年 https://github.com/TommyLemon/APIJSON . All rights reserved.//import UIKitclass ViewController: UIViewController {override func viewDidLoad() {super.viewDidLoad()// Do any additional setup after loading the view, typically from a nib.test()}override func didReceiveMemoryWarning() {super.didReceiveMemoryWarning()// Dispose of any resources that can be recreated.}/*** 通过POST请求测试APIJSON*/func test() {let url = "http://apijson.cn:8080/get";//要发送的请求数据let json = [//返回数据太长 "[]": ["User": [ //如果对象value是空的,请用[:]表示value,否则会被Swift解析为空数组[],而不是空对象{}"sex": 1]//]]let req = toJSONString(json);print("start http request...\n\nURL = " + url + "\nRequest = \n" + req)//生成UI <<<<<<<<<<<<<<<<<<<<<<let requestLabel = UILabel(frame:CGRect(x:20, y:10, width:400, height:130))requestLabel.text = "Request:\n" + req;requestLabel.numberOfLines = 6self.view.addSubview(requestLabel)let responseLable = UILabel(frame:CGRect(x:20, y:130, width:400, height:600))responseLable.text = "request..."responseLable.numberOfLines = 100self.view.addSubview(responseLable)//生成UI >>>>>>>>>>>>>>>>>>>>>//请求URLlet request:NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: url)!)request.HTTPMethod = "POST"//设置发送的数据格式为JSONrequest.setValue("application/json", forHTTPHeaderField: "Content-Type")do {request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)} catch {print("Something went wrong!")}//默认session配置let config = NSURLSessionConfiguration.defaultSessionConfiguration()let session = NSURLSession(configuration: config)//发起请求let dataTask = session.dataTaskWithRequest(request) { (data, response, error) inprint("\n\nreceived result!\n\n")print(data)print(response)print(error)//数据类型转换let jsonData:NSDictionary = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSDictionaryprint(jsonData)let res:String = self.toJSONString(jsonData);print("Response = \n" + res)//显示返回结果dispatch_async(dispatch_get_main_queue(), {responseLable.text = "Response:\n" + resprint("set text end\n\n")});}//请求开始dataTask.resume()}func toJSONString(jsonData: NSDictionary!) -> String {let data : NSData! = try? NSJSONSerialization.dataWithJSONObject(jsonData, options: [NSJSONWritingOptions.PrettyPrinted]) as NSData!let str = String(data: data, encoding: NSUTF8StringEncoding)return str!}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。