首页 > 代码库 > Swift3.0封装 AFN 的 GET&POST网络请求
Swift3.0封装 AFN 的 GET&POST网络请求
//// PSNetWorkManage.swift// WeiBoSwift//// Created by 思 彭 on 16/9/25.// Copyright © 2016年 思 彭. All rights reserved.//import UIKitimport AFNetworking// Swift的枚举支持任意数据类型,不需要,分隔enum PSHTTPMethod{ case GET case POST}/// 网络管理工具class PSNetWorkManage: AFHTTPSessionManager { // 单例 static let shared = PSNetWorkManage() // MARK:- get请求 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 =http://www.mamicode.com/ data { if let result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments){ success(result) } }else { failure(error!) } } dataTask.resume() } // MARK:- 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 =http://www.mamicode.com/ data { if let result = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) { success(result) } }else { failure(error!) } } dataTask.resume() }}
Swift3.0封装 AFN 的 GET&POST网络请求
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。