【问题标题】:Nested Alamofire Requests嵌套的 Alamofire 请求
【发布时间】:2015-08-18 15:37:05
【问题描述】:

我正在发出嵌套的 Alamofire 请求并使用返回的数据填充我的类属性对象。第一个 Alamofire 请求有效,我可以在第一个 Alamofire 请求中将数据注入我的类对象,但是第二个请求,虽然我看到从我的 API 返回的数据,但我无法将数据附加到我的类属性,这是一个如果是城市,则为数组。

 // Get States
getStatesByUserID(userID) {
    (result)->() in
    var states = JSON(result)
    for index in 0... states.count - 1 {
        let statesID: Int = states[index]["stateID"].intValue
        let statesName: String = states[index]["title"].stringValue


        // Get Cities by State ID
        self.getCities(stateID) {
            (result) -> () in
            let cities = JSON(result)
            for index in 0...cities.count - 1 {
                let cityID: Int = cities[index]["cityID"].intValue
                let cityName: String = cities[index]["title"].stringValue

                //Append a single city into cities array
                self.city.append(City(id: cityID, name: cityName))
            }
        }

        // Append a single state that contains cities and zips into states array
        self.state.append(State(id: stateID, name: stateName, city:self.city ))
    }
}
self.tableView.reloadData()
}

【问题讨论】:

  • 如果您发现问题并非如此,我试图提供一个我认为正在发生的事情的答案,请告诉我帮助您解决它

标签: ios iphone swift alamofire


【解决方案1】:

Alamofire 异步工作,如果您的第二个请求取决于第一个请求,并且您尝试将数据附加到同一个回调中,则可能是您要求尚未检索到的数据。如果是这种情况,您可以等到第一个请求完成他的工作,例如:

   public func SendPicAndSig(ip: String, enerImg: EnerImage, callBack:((JSONData:JSON)->Void)?){
    let address:String = "http://\(ip)/Enercard.Service/api/UploadFiles"

    let serial =  JSONSerializer.toJson(enerImg)
    let _parametros = JSONSerializer.toDictionary(serial) as! [String : AnyObject]

    debugPrint(_parametros)
    Alamofire.request(.POST,address, parameters: _parametros, encoding:.JSON)
        .responseJSON { _,_,result in
            switch result
            {
            case .Success(let data):
                //posible handling de error de parte del servidor
                debugPrint(result.data)
                  callBack?(JSONData: JSON(data))
            default:()
                break
            }
    }
}

这里我有一个示例函数,用于发送和对象,并且我将 CallBack 用作参数,此回调方法仅在成功检索数据时运行,因此我以后可以将此函数称为

SendPicAndSif("10.11.1.217" , Image("random-path"),SecondRequest)

如果我检索第一个请求的数据,“SecondRequest”将是我将运行的函数

SecondRequest(jsonarray:JSON)
{
  //second  Alamofire request
}

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多