如何在Swift3中将alamofire与对象映射器一起使用以在数组内部映射数组? [英] How to use alamofire with object mapper in Swift3 to map an array inside an array?

查看:50
本文介绍了如何在Swift3中将alamofire与对象映射器一起使用以在数组内部映射数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从响应中得到以下数组:

I have the following array which i am getting from Response:

如何在用逗号分隔的单个字符串中获取每个id的operatingDay值,例如:Mon ,Tue,Wed ....目前,我正在整个数组中获得cashPointsOperatingDays。如何编写Swift3代码?

How to get the value of operatingDay for each id in a single string separated by commas eg: Mon,Tue,Wed.... Currently I am getting the cashPointsOperatingDays in an array as a whole. How can I write the Swift3 code?

使用对象映射器:

// MARK: Travel Shops Mapper
class GetTravelShopsResponse: Mappable {
    var message: String?
    var status: Int?
    var travelShopsData: [TravelShopsResponse]?
    var cashCollectionsDateTimeData: [CashCollectionsDateTime]?
    // var threeDayForecast: [TravelShopsResponse]?
    required init?(map: Map) {
        mapping(map: map)
    }
    func mapping(map: Map) {
        message    <- map["messages"]
        status    <- map["status"]
        travelShopsData <- map["data"]
    }
}

class TravelShopsResponse: Mappable {
    var messages: String?
    var name: String?
    var address: String?
    var phoneNumber: String?
    var latitude: Float?
    var longitude: Float?
    var cashPointOperatingDays: [Any]?
    var locationid: String?
    required init?(map: Map) {
        mapping(map: map)
    }
    // Mappable
    func mapping(map: Map) {
        name  <- map["name"]
        address    <- map["address"]
        phoneNumber <- map["phoneNumber"]
        latitude       <- map["latitude"]
        longitude       <- map["longitude"]
        cashPointOperatingDays       <- map["cashPointOperatingDays"]
        locationid       <- map["id"]
    }
}

在我看来,控制器:

    //
import UIKit
import AlamofireObjectMapper
import Alamofire
class VPContactUsTravelShopsController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    @IBOutlet weak var travelShopsTableView: UITableView!
    @IBOutlet weak var showallTravelShopsLabel: UILabel!
    var yourArray = [Any]()
    var nameArray = [Any]()
    var addressArray = [Any]()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        getTravelShopsApiCall(URL:travelShopsURL!as URL)
    }
    // MARK: - UITableView delegates and datasources
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       return yourArray.count
            }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            if  let cell = tableView.dequeueReusableCell(withIdentifier: "location", for: indexPath) as? TravelShopCustomCell {
            cell.travelShopName.text = self.nameArray[indexPath.row] as? String
            cell.addressTextView.text = self.addressArray[indexPath.row] as? String
            //var cashPointArray = cashPointOperatingDays["indexPath.item"]
            return cell
            } else {
            fatalError("Dequeueing SomeCell failed")
            }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
                    return 480
    }
    // MARK: - Get Contact Us API call
    func getTravelShopsApiCall(URL: URL) {
        Alamofire.request(URL, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
            .responseObject { (response: DataResponse<GetTravelShopsResponse>) in
                print(response.result.value!)
                switch response.result {
                case .success:
                    if !(response is NSNull) {
                        // optional is NOT NULL, neither NIL nor NSNull
                        guard let end = response.result.value else {
                            return
                        }
                        DispatchQueue.main.async {
                            //end = nullToNil(end.loginAuthenticationInfo?.accessToken)
                            self.yourArray = end.travelShopsData!
                            var dataArray = [Any]()
                            print(self.yourArray)
                            if let threeDayForecast = end.travelShopsData {
                                for forecast in threeDayForecast {
                                    self.nameArray.append(forecast.name as Any)
                                    self.addressArray.append(forecast.address as Any)
                                    dataArray.append(forecast.cashPointOperatingDays as Any)
                                    print(forecast.name as Any)
                                    print(forecast.address as Any)
                                    print(forecast.phoneNumber as Any)
                                    print(forecast.latitude as Any)
                                    print(forecast.longitude as Any)
                                    print(forecast.cashPointOperatingDays as Any)
                                                                                        }
                            }
//                            if let cashCollectionsDateTime = end.cashCollectionsDateTimeData {
//                                for operationDetails in cashCollectionsDateTime {
//                                    self.cashPointOperatingDaysArray.append(operationDetails.day as Any)
//                                    
//                                }
//                            }

                            self.travelShopsTableView.reloadData()
                        }
                    } else {
                        // null
                    }
                    break
                case .failure:
                    if let error = response.result.error as? URLError {
                        print("URLError occurred: \(error)")
                    } else {
                        print("Unknown error: \(String(describing: response.result.error))")
                    }
                    break
                }
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


推荐答案

我尚未在XCode或Playground上测试此代码,因此请检查一下。
我认为此代码段可用于附加cashPointOperatingDays数组。

I have not tested this code on XCode or playground, so mind checking it. I think this code snippet can be used in appending the array of cashPointOperatingDays.

for cashPointOperatingDay in cashPointOperatingDays {
    cashPointOperatingDays.append(cashPointOperatingDay)
}

这应该在您的<$ c $ p>

This should be in your TravelShopsResponse class beneath the declaration of

 cashPointOperatingDays <- map["cashPointOperatingDays"]

为了进行检索,我们可以在tableView或collectionView中使用 cellForRow 方法:

And for retrieving, we can use in a tableView or collectionView cellForRow method:

var cashPointArray = cashPointOperatingDays["indexPath.item"]
let retrieveArray = cashPointArray["operatingDay"]
print(retrieveArray)

再次,请在您的代码中对其进行检查

Again, please check it in your code.

这篇关于如何在Swift3中将alamofire与对象映射器一起使用以在数组内部映射数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆