美文网首页
Swift网络请求(二)

Swift网络请求(二)

作者: Hunter琼 | 来源:发表于2018-11-01 14:48 被阅读13次

1 pod install AFNetworking

pod ‘AFNetworking’,’~> 3.0.4’
use_frameworks!

2 SWURLSessionManger类引入头文件#import AFNetworking ,继承于AFHTTPSessionManger

class SWURLSessionManger: AFHTTPSessionManager {
    
  static let shareSessionManger:SWURLSessionManger = { () -> SWURLSessionManger in
    let manager = SWURLSessionManger()
    //manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
    manager.responseSerializer = AFHTTPResponseSerializer.init()
    manager.requestSerializer.timeoutInterval = 30
    return manager
     }()
    /**
     * param method:请求方式 默认GET
     * param urlString:请求地址
     * param parameters:参数
     * completed:回调结果
     @author wenze
    **/
    func swReqeust(method:SWURLRequestMethod = .GET ,urlString:String,parameters:[String:AnyObject]?,completed:@escaping((_ json:AnyObject?,_ isSuccess:Bool)->())){
        /** 成功回调闭包 */
        let success = {
            (task:URLSessionTask?,json:Any?)->() in completed(json as AnyObject,true)
        }
        /** 失败回调闭包*/
        let failure = {
            (task:URLSessionTask?,json:Any?)->() in completed(json as AnyObject,false)
        }
        /** 请求*/
        if method == .GET {
          get(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
        }else{
          post(urlString, parameters: parameters, progress: nil, success: success, failure:failure)
        }
    }
    
    /**
     * @explation:NSdata转化成NSDictionary
    **/
    func dataToDictionary(data:Data) -> Dictionary<String,Any> {
        do {
            let json =  try JSONSerialization.jsonObject(with: data as Data, options: .mutableLeaves)
            return json as! Dictionary<String,Any>
        } catch _  {
            /**错误解析*/
             return Dictionary.init()
        }
    }
    
}

3 请求

 SWURLSessionManger.shareSessionManger.swReqeust(method: SWURLRequestMethod.GET, urlString: "https://", parameters:nil,completed: { (json:AnyObject?, isSuccess:Bool) in
            //print("json=\(String(describing: json))")
            let jsonDic = SWURLSessionManger.shareSessionManger.dataToDictionary(data: json as! Data)
            print(jsonDic)
            
         
        })

demo地址:https://github.com/joinGitWenze/NetRequestOrJsonAnalysisSwift

相关文章

网友评论

      本文标题:Swift网络请求(二)

      本文链接:https://www.haomeiwen.com/subject/pokxxqtx.html