• NSURLSession -- 实际开发中运用


    NSURLSession实际请求

    iOS9使用http请求方法:

    1. 在工程info.plist文件内添加NSAppTransportSecurity键,类型为dictionary
    2. 在NSAppTransportSecurity中添加NSAllowsArbitraryLoads键,值为YES

    GET请求

            let key = "a27383fa93bd3cc57ff4a180036d56ac"
            let urlString = "http://v.juhe.cn/xianxing/citys"
            let url = NSURL(string: urlString + "?key=" + key)
            
            // 创建请求对象
            let request = NSURLRequest(URL: url!)
            
            // 获取会话对象
            let session = NSURLSession.sharedSession()
            
            // 创建请求任务
            let task = session.dataTaskWithRequest(request) { (data, response, error) in
                if let jsonData = data {
                    do {
                        let dic = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? [String : AnyObject]
                        print(dic)
                    } catch {
                        
                    }
                }
            }
            
            // 执行任务
            task.resume()
    

    POST请求

            let urlString = "http://v.juhe.cn/carzone/series/query"
            let url = NSURL(string: urlString)
            
            // 创建请求对象
            let request = NSMutableURLRequest(URL: url!)
            // 设置请求模式
            request.HTTPMethod = "POST"
            // 设置请求体
            request.HTTPBody = "action=getCarAllBrand&key=afdfb2885044bf2e14b24c293012bbea".dataUsingEncoding(NSUTF8StringEncoding)
            
            
            // 获取会话对象
            let session = NSURLSession.sharedSession()
            
            // 创建请求任务
            let task = session.dataTaskWithRequest(request) { (data, response, error) in
                if let jsonData = data {
                    do {
                        let dic = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? [String : AnyObject]
                        print(dic)
                    } catch {
                        
                    }
                }
            }
            
            // 执行任务
            task.resume()
    
  • 相关阅读:
    单线程的JavaScript是如何实现异步的
    前端优化之 -- 使用 require.context 让项目实现路由自动导入
    插入排序
    选择排序
    冒泡排序
    强缓存和协商缓存
    ES6 Set求两个数组的并集、交集、差集;以及对数组去重
    实现一个new操作符
    我理解的浅拷贝和深拷贝
    javascript专题系列--js乱序
  • 原文地址:https://www.cnblogs.com/Alex-sk/p/5574159.html
Copyright © 2020-2023  润新知