如何在Swift3中使用带有对象映射器的alamofire来映射数组中的数组?

时间:2017-06-25 04:43:10

标签: ios arrays swift3 alamofire

我有以下数据,我从Response:

获得

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

使用Object Mapper:

// 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.
    }
    */

}

1 个答案:

答案 0 :(得分:0)

我没有在XCode或操场上测试过这段代码,所以请仔细检查。 我认为这段代码片段可用于附加cashPointOperatingDays数组。

string sourceUrl = "https://www.webiste/mad.dll";
        string targetdownloadedFile = @"C:\\temp\\mad.dll";

        DownloadFile(sourceUrl, targetdownloadedFile);

这应该在

声明下方的for cashPointOperatingDay in cashPointOperatingDays { cashPointOperatingDays.append(cashPointOperatingDay) } 课程中
TravelShopsResponse

对于检索,我们可以在tableView或collectionView cashPointOperatingDays <- map["cashPointOperatingDays"] 方法中使用:

cellForRow

再次,请在您的代码中查看。