Swift学习iOS之Swift开发程序员

Swift3.0 使用AFN进行网络请求

2017-05-05  本文已影响104人  ArchLL

前言:

最近项目要求混编,还要求使用Swift3.0 还要适配 iOS8.0以上,想来想去还是使用AFN进行网络请求比较问稳妥。

接下来我们就封装一个AFN请求类,实现简单的GET请求和POST请求
1. 先创建一个类文件 SwiftNetWorkManager.swift

注意:这里引入AFNetworking,不是在桥接文件里面引入,而是在你需要使用的swift文件头部引入
代码如下:

import UIKit
import AFNetworking

enum RequestType {
    case GET
    case POST
}

class SwiftNetWorkManager: AFHTTPSessionManager {
 
    static let shareInstance : SwiftNetWorkManager = {
        let tool = SwiftNetWorkManager()
        tool.requestSerializer = AFHTTPRequestSerializer()
        tool.responseSerializer = AFJSONResponseSerializer()
        tool.responseSerializer.acceptableContentTypes?.insert("text/html")
        tool.requestSerializer.timeoutInterval = 10
        return tool
    }()
    
    func request(requestType: RequestType, url : String, params: [String : Any], success: @escaping([String : Any]?) ->(),failure: @escaping( _ error : Error?) -> ()){
        //成功
        let successBlock = { (task: URLSessionDataTask, responseObj: Any?) in
            success(responseObj as? [String : Any])
        }
        
        //失败
        let failureBlock = {(task : URLSessionDataTask?,error:Error) in
            failure(error)
        }
        
        //GET
        if requestType == .GET {
            get(url, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
            //get(url, parameters: params, success: successBlock, failure: failureBlock)
        }
        
        //POST
        if requestType == .POST {
            post(url, parameters: params, progress: nil, success: successBlock, failure: failureBlock)
            //post(url, parameters: params, success: successBlock, failure: failureBlock)
        }
    }
}
2. 使用SwiftNetWorkManager.swift 进行网络请求(以GET请求为例)
       let params1 = ["type":"minute","Label":"SH000002"]
       SwiftNetWorkManager.shareInstance.request(requestType: .GET, url: ChartTestPort, params: params1, success: { (responseObj) in
            print(responseObj!)
            if responseObj?["rows"] as? Int == 0 {
              //解析数据
                
            }
        }) { (error) in
            print(error!)
        }
上一篇下一篇

猜你喜欢

热点阅读