我想創建包含我所有請求的AlamofireWebService管理器,並且只在我的viewControllers中使用此類的類函數並在viewController中使用響應。
例如像這樣的的viewController:
Alamofire Web服務管理器在viewController中返回nil
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它只是打印零。
我的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打印打印我的反應?
是的,這是一個陣列非常感謝你 – arash