首页 > 解决方案 > 数据响应 Swift 4 Timer 时的 Alamofire

问题描述

我有一个 Alamofire 函数,比如当数据将数据插入 Global NsDictionary

Common.Customers

功能是

static func PostAlomofire(format : RequestFormat)  {

    let loginParam: [String: Any] = [
        "searchTerm": format.Name,
        "pageSize": format.PageSize,
        "pageNumber": format.PageNumber ,
        "deviceId": format.DeviceId
    ]
print(loginParam)

  Alamofire.request("http://111.3.4.2/website/api/Customer/Search", method: .post, parameters: loginParam, encoding: JSONEncoding.prettyPrinted)
        .responseJSON { response in    
            let result = response.result
            print(result.value)
            if let dict = result.value as? Dictionary<String,AnyObject>
            {
                if let innerDic = dict["results"]
                {

                    Common.Customers = innerDic as! [NSDictionary]
                }
            }
            print(Common.Customers)
    }

}

此代码正在运行。但是,如果我不使用计时器Common.Customers总是为零。当我想调用这个函数时,我正在调用

  WebService.PostAlomofire(format: format)
    _ = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: false) { timer in
        self.Table_tv.reloadData()

    }

但如果数据没有出现 0.5 秒,则此代码不起作用。

Timer.scheduledTimer

是不是正确的方法?我觉得不安全。如果它不是真的,我可以使用什么?

标签: iosswiftuitableviewasynchronousalamofire

解决方案


您需要创建一个完成处理程序,因为这不是计时器的工作

static func PostAlomofire(format : RequestFormat,completion:@escaping(()-> Void)) {
       let loginParam: [String: Any] = [
    "searchTerm": format.Name,
    "pageSize": format.PageSize,
    "pageNumber": format.PageNumber ,
    "deviceId": format.DeviceId
]
print(loginParam)

 Alamofire.request("http://111.3.4.2/website/api/Customer/Search", method: .post, parameters: loginParam, encoding: JSONEncoding.prettyPrinted)
    .responseJSON { response in    
        let result = response.result
        print(result.value)
        if let dict = result.value as? [String: Any]
        {
            if let innerDic = dict["results"]
            {

                Common.Customers = innerDic as! [[String: Any]]
                completion()
            }
        }
        print(Common.Customers)
}
}

//

WebService.PostAlomofire(format: format) {
     self.Table_tv.reloadData()
}

推荐阅读