2015-09-15 25 views
1

使用的Xcode 7.1遍歷對象斯威夫特 - 陣列出指數 - AlamofireObjectMapper在TableView中

我試圖做一個請求以下JSON,並顯示在一個的tableView

我使用AlamofireObjectMapper到JSON轉換對象。

問題:我不知道如何來遍歷對象的tableView

下面是自定義類,Alamofire請求&的TableView

class WeatherResponse: Mappable { 
var location: String? 
var threeDayForecast: [Forecast]? 

required init?(_ map: Map){} 

func mapping(map: Map) { 
    location <- map["location"] 
    threeDayForecast <- map["three_day_forecast"] 
} 
} 

class Forecast: Mappable { 
var day: String? 
var temperature: Int? 
var conditions: String? 

required init?(_ map: Map){} 

func mapping(map: Map) { 
    day <- map["day"] 
    temperature <- map["temperature"] 
    conditions <- map["conditions"] 
} 
} 

Alamofire請求

//Defined within ViewController 
var location: String? 
var arrayOfForecasts = [Forecast]() 

override func viewDidLoad() { 
Alamofire.request(.GET, url).responseObject{(response :WeatherResponse?, error: ErrorType?)in 
     let location1 = response?.location 
     self.location = location1 

    let threeDayForecast1 = response?.threeDayForecast 
     self.arrayOfForecasts = threeDayForecast1! 
     print(threeDayForecast1) 
     self.tableView.reloadData() 
    } } 

當我 '打印(threeDayForecast1)' 我得到以下輸出: [MyAppName.Forecast,MyAppName.Forecast,MyAppName.Forecast]

的TableView協議

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! TableViewCell 
    let threeDayObj1 = arrayOfForecasts[indexPath.row] 
    cell.tempLabel?.text = threeDayObj1.conditions 

    return cell 
} 

我得到錯誤如下:

threeDayObj1 is array out of index 
+0

你從哪裏得到錯誤? threeDayObj1是三天? – ciccioska

+0

對不起,有一個錯字錯誤..我糾正了它..錯誤是在行threeDayObj1 = arrayOfForecasts [indexPath.row] –

回答

0

在最新版本的AlamofireObjectMapper中,使用Swift 3,Xcode 8和iOS 10,您需要執行打電話如下:

Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).validate().responseObject { (response: DataResponse< WeatherResponse>) in 
...