Alamofire Web服务管理器在viewController

时间:2017-07-12 09:30:38

标签: ios swift3 uiviewcontroller alamofire

我想创建包含我所有请求的AlamofireWebService管理器,我只在viewControllers中使用此类的类函数,并使用viewController中的响应。
例如viewController中的类似内容:

 let cardResponse : String?
 cardResponse = WebServiceManager.shared.getCardTitle()

我搜索并发现我应该在我的函数中使用转义completionHandler而我写了这个:

import Foundation
import Alamofire
import SwiftyJSON

class WebServiceManager {

    static let shared : WebServiceManager = WebServiceManager()

    let apiEndPoint = "My URL"

    func getCardTitle(completionHandler: @escaping (NSDictionary?, Error?) -> ()) {
        Alamofire.request("\(apiEndPoint)")
            .responseJSON { response in
                switch response.result {
                case .success(let value):
                      print("from .success \(value)")
                      completionHandler(value as? NSDictionary, nil)
                case .failure(let error):
                      completionHandler(nil, error)
                }
        }

    }
}

在成功的情况下,打印工作正常,但在viewController中,它只打印nil。

我的viewController

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    WebServiceManager.shared.getCardTitle() { responseObject, error in
        // use responseObject and error here

        print("responseObject = \(responseObject); error = \(error)")
        return
    }

}

我应该如何打印viewController打印我的回复?

2 个答案:

答案 0 :(得分:1)

这意味着你的值不能转换为NSDictionary它有另一种类型。

completionHandler(value as? NSDictionary, nil)

请在经理中尝试“伪代码”

if let dic = value as? [String: Any] {
   debugPrint("Dic \(dic)")
} else  if let str = value as? String {
   debugPrint("String \(str)")
} else if let data = value as? Data, let str = String(data: data, encoding: .utf8) {
   debugPrint("UTF8 String \(str)")
} 

答案 1 :(得分:0)

只检查响应

     Alamofire.request("URL", method: .post).responseJSON{(responseData) -> Void in
        if((responseData.result.value != nil)){
            let jsonData = JSON(responseData.result.value)

            if let arrJSON = jsonData["keyNodes"].arrayObject {

                for index in 0...arrJSON.count-1 {
                    let aObject = arrJSON[index] as! [String : AnyObject]
                    var sl:String;
                    if let sl1 = aObject["sl"] as? String {
                        sl = sl1;
                    }
                }
            }

        }
    }