美文网首页
swift学习笔记 -Alamofire的封装调用

swift学习笔记 -Alamofire的封装调用

作者: 妃雪 | 来源:发表于2017-03-23 16:02 被阅读216次

    最近在学习swift,在项目中遇到网络解析的时候遇到不少问题。分享下之后的解决方案。

    (1)对Alamofire 进行封装。代码如下:

    import UIKit
    import Alamofire
    
    enum MethodType {
        case get
        case post
    }
    
    class HttpTools {
        //可根据需要传参数
        class func requestData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback :  @escaping (_ result : Any) -> ()) {
            let method = type == .get ? HTTPMethod.get : HTTPMethod.post
            Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
                guard let result = response.result.value else {
                    print(response.result.error ?? -1)
                    return
                }
                finishedCallback(result)
            }
        }
    }
    

    (2)在viewcontroller 进行调用

     func requestData(finishedCallback : @escaping () -> ()) {
            let parameters: Parameters = [
                "curDateStr": "2017-03-22",
                "curPage": 1,
                "pageSize":10
            ]
            loadAnchorData(isGroupData: true, URLString: "url",parameters:parameters ,finishedCallback: finishedCallback)
        }
        
     func loadAnchorData(isGroupData : Bool, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping () -> ()) {
            HttpTools.requestData(.post, URLString: URLString, parameters: parameters) { (result) in
                print(result)
                guard let dict = result as? [String : Any] else { return }
                guard let arr = dict["data"] as? [[String : Any]] else { return }
                if isGroupData {
                    for dict in arr {
                       // self.anchorGroups.append(AnchorGroup(dict: dict))
                    }
                } else  {
    //                let group = AnchorGroup()
    //                for dict in arr {
    //                    group.anchors.append(AnchorModel(dict: dict))
                    }
                    //self.anchorGroups.append(group)
                }
                finishedCallback()
            }
    

    相关文章

      网友评论

          本文标题:swift学习笔记 -Alamofire的封装调用

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