iOS 每天一读

Swift3.0蛋蛋忧伤的邂逅之网络请求

2016-09-29  本文已影响156人  Easy_VO

前言:

swift这个不稳定,真的是蛋疼无比,尤其是语法变更。第三方更新不及时,也导致很多问题。anyway闲暇之余手里不忙来“深入浅出”的学习一下皮毛。

zm.jpg
接昨天做的Swift中自定义cell,来进一步模仿着项目的进行~

在swift中再不想oc一样.h/.m分明,讲道理最开始接触oc的时候觉得这样才好啊,声明和实现分开写。不过后来写swift又觉得写在一个.swift里这么写也很爽。

具体实现步骤:

1.新建一个类,姑且取名为VDNetTools吧
2.在其中进行网络请求的书写吧

GET请求

//单例
   static let share = VDNetTools()

func getWithPath(path: String,paras: Dictionary<String,Any>?,success: @escaping ((_ result: Any) -> ()),failure: @escaping ((_ error: Error) -> ())) {
    
    var i = 0
    var address = path
    if let paras = paras {
        
        for (key,value) in paras {
            
            if i == 0 {
                
                address += "?\(key)=\(value)"
            }else {
                
                address += "&\(key)=\(value)"
            }
            
            i += 1
        }
    }
    
    let url = URL(string: address.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)
    
    let session = URLSession.shared
    
    let dataTask = session.dataTask(with: url!) { (data, respond, error) in
        
        if let data = data {
            
            if let result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments){
                
                success(result)
            }
        }else {
            
            failure(error!)
        }
    }
    dataTask.resume()
}

POST请求

 func postWithPath(path: String,paras: Dictionary<String,Any>?,success: @escaping ((_ result: Any) -> ()),failure: @escaping ((_ error: Error) -> ())) {
    
    var i = 0
    var address: String = ""
    
    if let paras = paras {
        
        for (key,value) in paras {
            
            if i == 0 {
                
                address += "\(key)=\(value)"
            }else {
                
                address += "&\(key)=\(value)"
            }
            
            i += 1
        }
    }
    let url = URL(string: path)
    var request = URLRequest.init(url: url!)
    request.httpMethod = "POST"
    print(address)
    request.httpBody = address.data(using: .utf8)
    let session = URLSession.shared
    let dataTask = session.dataTask(with: request) { (data, respond, error) in
        
        if let data = data {
            
            if let result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) {
                
                success(result)
            }
            
        }else {
            failure(error!)
        }
    }
    dataTask.resume()
}

怎么使用呢

 @objc fileprivate func loadData() {
    
    let path = "请求的地址"
//        let dict = ["userid":1]
    VDNetTools.share.getWithPath(path: path, paras: nil, success: { (result) in
        
//            print(result)
        
        //如果设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读
        let data = try? JSONSerialization.data(withJSONObject: result, options: JSONSerialization.WritingOptions.prettyPrinted)
        //Data转换成String打印输出
        let str = String(data:data!, encoding: String.Encoding.utf8)
        
        //输出json字符串
        print("Json Str:"); print(str)
    
        
        }) { (error) in
        
        print(error)
    }
}

结语:

这是一种蛋疼的体验,只等swift稳定再投入战斗中吧

上一篇下一篇

猜你喜欢

热点阅读