2015-11-02 53 views
0

我有一個表格視圖,7行星期一,星期二,......,星期天。更新基於Web服務實現的行標籤swift

({ 
    appointments = (
        { 
        numApts = 1; 
        scheduleDate = "2015-11-02"; 
        }, 
        { 
        numApts = 2; 
        scheduleDate = "2015-11-04"; 
        } 
       ); 
}) 

所以我通過JSON響應試圖循環,如果在收到的JSON的日期相匹配更新我們平日的標籤:我的應用程序從一個Web服務,這是格式接收一個JSON。

不知道如何實現這一點。我需要模特班嗎?喜歡的東西:

import UIKit 

class CurrentRosterModel { 
    var numApts : String? 
    var scheduleDate : String? 

    init(json : NSDictionary){ 
     self.numApts = json["numApts"] as? String 
     self.scheduleDate = json["scheduleDate"] as? String 
    } 
} 

我今天是想用一個函數來更新行中的文本,像這樣的,但我沒有進入決賽,如果讓條件接入小區,以便更新標籤:

let weekDateDict = ["Monday" : mon, "Tuesday" : tues, "Wednesday" : wedns, "Thursday" : thurs, "Friday" : fri, "Saturday" : sat, "Sunday" : sun] 
    //where vars mon = "2015-11-02", tues = "2015-11-03" etc. 
      //aptsArray is hard coded for now but will need to come from a web service response later 
      let aptsArray : [Dictionary<String, String>] = [ 
       [ 
        "numApts" : "1", 
        "scheduleDate" : "2015-11-02" 
       ], 
       [ 
        "numApts" : "2", 
        "scheduleDate" : "2015-11-04" 
       ]]; 



      for (weekDay, weekDate) in weekDateDict { 
       if aptsArray.contains({ $0.values.contains(weekDate)}) { 
        print("Matched with weekDate is \(weekDate) and weekDay is \(weekDay)") 
        //getting this condition twice as expected 
        let ourIndexPath : NSIndexPath? 
        switch weekDay { 
         case "Monday": 
          ourIndexPath = NSIndexPath(forRow: 0, inSection : 0) 
          //print("Monday label update") 
         case "Tuesday": 
          ourIndexPath = NSIndexPath(forRow: 1, inSection : 0) 
          //print("Tuesday label update") 
         case "Wednesday": 
          ourIndexPath = NSIndexPath(forRow: 2, inSection : 0) 
          //print("Wednesday label update") 
         case "Thursday": 
          ourIndexPath = NSIndexPath(forRow: 3, inSection : 0) 
          //print("Thursday label update") 
         case "Friday": 
          ourIndexPath = NSIndexPath(forRow: 4, inSection : 0) 
          //print("Friday label update") 
         case "Saturday": 
          ourIndexPath = NSIndexPath(forRow: 5, inSection : 0) 
          //print("Saturday label update") 
         case "Sunday": 
          ourIndexPath = NSIndexPath(forRow: 6, inSection : 0) 
          //print("Sunday label update") 
        default : 
         ourIndexPath = NSIndexPath(forRow: 7, inSection : 0) 
         //print("swicth not satisfied") 
        } 

        if let cell = weekTableView.cellForRowAtIndexPath(ourIndexPath!) as? WeekDayCell{ 
         print("got in here")//not getting in here 
         cell.numAptsLbl.text = aptsArray[0]["numApts"]! 
         weekTableView.beginUpdates() 
         weekTableView.reloadRowsAtIndexPaths([ourIndexPath!], withRowAnimation: UITableViewRowAnimation.Automatic) 
         weekTableView.endUpdates() 

        } 

       } 

我的tableview方法如下所示:

func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
    return 1 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    return 7 
} 

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = weekTableView.dequeueReusableCellWithIdentifier("WeekDayCell", forIndexPath: indexPath) as! WeekDayCell 

    cell.dayLbl?.text = weekArray[indexPath.row] 
    cell.numAptsLbl?.text = "0" 
    //indexPath.row.description 
    //print("indexpath in tableview is \(indexPath)") 

    return cell 
} 

回答

0

假設

首先,你發佈的json示例不是有效的json,而是你在調試器中看到的輸出。我假設JSON將類似於以下格式的內容:

{ 
    "appointments": [ 
    { 
     "numApts": 1, 
     "title": "Coffee", 
     "scheduleDate": "2015-11-02" 
    }, 
    { 
     "numApts": 2, 
     "title": "Shower", 
     "scheduleDate": "2015-11-04" 
    }, 
    { 
     "numApts": 3, 
     "title": "Rollercoaster!!!!", 
     "scheduleDate": "2015-12-24" 
    } 
    ] 
} 

TL; DR

我建議你創建一個Appointment模型表示預約單。然後,您應該創建一個包裝器,用於存儲所有約會,並根據星期幾進行過濾。無論您認爲適合您的項目,您都可以命名此包裝。

代碼示例

我試圖拼湊最簡單的情況下你想實現什麼。希望代碼中使用的命名足以描述其自身。

我認爲這將有很多幫助來回答你的問題,並讓你從這裏出發。我的代碼的輸出將類似於下圖的內容:

Final app

現在,我需要強調的是有展開這裏和那裏,你需要知道一點力,在開始使用前在生產中就像這樣。

Appointment.swift

// 
// Appointment.swift 
// WeekDays 
// 
// Created by Stefan Veis Pennerup on 02/11/15. 
// Copyright © 2015 Kumuluzz. All rights reserved. 
// 

import Foundation 

struct Appointment { 

    // MARK: - Formatter 

    private static var DateFormatter: NSDateFormatter = { 
     let formatter = NSDateFormatter() 
     formatter.dateFormat = "yyyy-MM-dd" 
     return formatter 
    }() 

    // MARK: - Properties 

    let numApts: Int 
    let title: String 
    let scheduleDate: NSDate 

    // MARK: - Initializers 

    init(json: [String: AnyObject]) { 
     numApts = json["numApts"] as? Int ?? 0 
     title = json["title"] as? String ?? "" 
     let dateString = json["scheduleDate"] as? String ?? "" 
     scheduleDate = Appointment.DateFormatter.dateFromString(dateString) ?? NSDate() 
    } 
} 

WeekDaysModel.swift

// 
// WeekDays.swift 
// WeekDays 
// 
// Created by Stefan Veis Pennerup on 02/11/15. 
// Copyright © 2015 Kumuluzz. All rights reserved. 
// 

import Foundation 

enum WeekDay: Int { 
    // Sunday has been set as the initial index, because the NSDateComponents 
    // has been created with Sunday as the initial day with an index of 1. 
    // This is being taken into consideration in the getWeekDayIndexForDate() 
    case Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday 
} 

struct WeekDaysModel { 

    // MARK: - Properties 

    var appointments: [WeekDay: [Appointment]] = [ 
     WeekDay.Monday:[], 
     WeekDay.Tuesday:[], 
     WeekDay.Wednesday:[], 
     WeekDay.Thursday:[], 
     WeekDay.Friday:[], 
     WeekDay.Saturday:[], 
     WeekDay.Sunday:[] 
    ] 

    // MARK: - Initializers 

    init() {} 

    init(json: [String: AnyObject]) { 
     // Ensures there is data 
     guard let appointmentsJson = json["appointments"] as? [[String: AnyObject]] else { 
      return 
     } 

     // Parses the data points to the Appointment model 
     let apts = appointmentsJson.map { json in 
      return Appointment(json: json) 
     } 

     // Assigns each Appointment to a weekday 
     _ = apts.map { apt in 
      let i = getWeekDayIndexForDate(apt.scheduleDate) 
      appointments[WeekDay(rawValue: i)!]! += [apt] 
     }   
    } 

    // MARK: - Helpers 

    private func getWeekDayIndexForDate(aDate: NSDate) -> Int { 
     let cal = NSCalendar(identifier: NSCalendarIdentifierGregorian)! 
     let comp = cal.components(.Weekday, fromDate: aDate) 
     return (comp.weekday - 1) 
    } 
} 

ViewController.swift

// 
// ViewController.swift 
// WeekDays 
// 
// Created by Stefan Veis Pennerup on 02/11/15. 
// Copyright © 2015 Kumuluzz. All rights reserved. 
// 

import UIKit 

class ViewController: UITableViewController { 

    // MARK: - Properties 

    private var model = WeekDaysModel() { 
     didSet { 
      tableView.reloadData() 
     } 
    } 

    // MARK: - Lifecycle methods 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     Backend.downloadAppointments{ 
      self.model = $0 
     } 
    } 

    // MARK: - UITableViewDelegate 

    // MARK: - UITableViewDataSource 

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { 
     return model.appointments.count 
    } 

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return model.appointments[WeekDay(rawValue: section)!]!.count 
    } 

    override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { 
     return String(WeekDay(rawValue: section)!) 
    } 

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("myCell")! 
     let apts = model.appointments[WeekDay(rawValue: indexPath.section)!]! 
     cell.textLabel?.text = apts[indexPath.row].title 
     return cell 
    } 
} 

Backend.swift

// 
// Backend.swift 
// WeekDays 
// 
// Created by Stefan Veis Pennerup on 02/11/15. 
// Copyright © 2015 Kumuluzz. All rights reserved. 
// 

import Foundation 
import Alamofire 

struct Backend { 

    static func downloadAppointments(handler: (WeekDaysModel)->Void) { 
     let url = "http://stefanveispennerup.com/so.json" 
     Alamofire.request(.GET, url).responseJSON { response in 
      // TODO: Check response code, etc.. 
      if let json = response.result.value as? [String: AnyObject] { 
       let model = WeekDaysModel(json: json) 
       handler(model) 
      } 
     } 
    } 
}