基于Web服务实现快速更新行标签

2024-01-31

我有一个包含 7 行的表视图,周一、周二、......、周日。我的应用程序从 Web 服务接收一个 json,其格式为:

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

因此,我尝试循环 json 响应,并更新工作日的标签(如果它与收到的 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
    }
}

我今天尝试的是一个像这样更新行文本的函数,但我没有进入最终的 if let 条件来访问单元格以更新标签:

    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()

                    }

                }

我的表格视图方法如下所示:

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
}

假设

首先,您发布的 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代表单个约会的模型。然后,您应该创建一个包装器,用于存储所有约会,并根据工作日进行过滤。您可以为该包装器命名任何您认为适合您的项目的名称。

代码示例

我尝试为您想要实现的内容整理最简单的案例。希望代码中使用的命名具有足够的描述性以解释其本身。

我认为这对于回答您的问题并让您从这里开始有很大的帮助。我的代码的输出将类似于下图:

现在,我需要强调的是,在开始在生产中使用类似的东西之前,您需要注意这里和那里有一些力量展开。

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)
            }
        }
    }  
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

基于Web服务实现快速更新行标签 的相关文章

  • didReceiveRemoteNotification 未调用,iOS 10

    在 iOS 9 3 中 didReceiveRemoteNotification方法在以下两种情况下都会被调用 1 收到推送通知时 2 当用户通过点击通知启动应用程序时 但在 iOS 10 上 我注意到didReceiveRemoteNot
  • HTML 解析 - 从 div 内的表格获取数据?

    我对 HTML 解析 抓取的整个想法还比较陌生 我希望我能来这里获得我需要的帮助 基本上我想要做的 我认为 是指定我希望从中获取数据的页面的 url 在这种情况下 http www epgpweb com guild us Caelestr
  • WCF 自定义序列化器

    我正在 WCF 中创建一个返回 JSON 的 Web 服务 但 DataContractJsonSerializer 对某些循环引用犹豫不决 在这种特殊情况下我无法删除这些引用 相反 我想使用 Newtonsoft json 库 在 WCF
  • 如何创建指针数组?

    我正在尝试创建一个指针数组 这些指针将指向我创建的 Student 对象 我该怎么做 我现在拥有的是 Student db new Student 5 但该数组中的每个元素都是学生对象 而不是指向学生对象的指针 谢谢 Student db
  • 如何获取 iTunes connect 团队 ID 和团队名称?

    我正在写下一个Appfile for fastlane 我的问题是我已经有了team name and team id在 Apple 开发中心 但我无法获取iTunes Connect ID itc team id 我正在与不同的团队合作
  • Web API 复杂参数属性均为 null

    我有一个 Web API 服务调用可以更新用户的首选项 不幸的是 当我从 jQuery ajax 调用中调用此 POST 方法时 请求参数对象的属性始终为 null 或默认值 而不是传入的值 如果我使用 REST 客户端调用相同的方法 我使
  • 如何在不使用反射的情况下查看对象是否是数组?

    在Java中如何在不使用反射的情况下查看对象是否是数组 如何在不使用反射的情况下迭代所有项目 我使用 Google GWT 所以不允许我使用反射 我很想在不使用反射的情况下实现以下方法 private boolean isArray fin
  • NSString cString 已弃用。还有什么选择呢?

    我还有一个新手问题 我编写了一段代码 将 NSString 转换为 NSMutableData 以模拟 webService 结果 然而事实证明 cString 已被弃用 你能帮我更换它吗 这是我的代码 NSString testXMLDa
  • 在 C++ 中从另一个数组初始化结构内的数组[关闭]

    这个问题不太可能对任何未来的访客有帮助 它只与一个较小的地理区域 一个特定的时间点或一个非常狭窄的情况相关 通常不适用于全世界的互联网受众 为了帮助使这个问题更广泛地适用 访问帮助中心 help reopen questions struc
  • 如何以编程方式创建 Unwind segue

    我制作了一个不使用故事板的应用程序 在我的应用程序的这一部分中 我需要创建一个展开转场ThirdViewController to FirstViewController仅以编程方式 我知道如何使用 sotorybard 执行此操作 但找不
  • Android AsyncTask 第二次调用时未执行

    我有一个扩展 AsyncTask 的类 public class SendJSONArray2Server extends AsyncTask
  • 有什么办法可以将2个数组添加到一个数组中吗?

    有没有一种简单通用的方法可以将两个数组添加到一个数组中 在下面的情况下 不可能简单地使用C A B陈述 我想避免每次都为它制定算法 TPerson record Birthday Tdate Name Surname string end
  • 如何从 UITableViewController 中的静态单元格获取文本字段?迅速

    我的视图层次结构如下所示 UIViewController 类型的 ElevethViewController容器视图嵌入容器视图中的 UITableViewController 类型的 ManagedTableEleventhViewCo
  • 扩展功能截图未捕获 iPhone 和 iPad 中的同一区域

    我正在使用扩展函数来截取 uiview 的屏幕截图 问题是结果看起来非常不同 我希望无论使用 ipad 还是 iphone 照片看起来都一样 我手动输入约束 因此我希望图像是相同的 我想使用该函数转到视图控制器的原点或中心 高度为 200
  • 使用 JSON 传递 HTML

    我正在使用 JSON 将数据传递到 iPhone 和 iPad 数据的一个字段是 HTML 问题是编码 这是我得到的回复 gt GadgetHTML strong Hello strong gt from Catworld br n img
  • 还有比这更好的方法在通知附件中使用 Assets.xcassets 中的图像吗?

    我想将 Assets xcassets 中的图像附加到通知中 我已经寻找解决方案大约一个小时了 这似乎是执行此操作的唯一方法 func createLocalUrl forImageNamed name String gt URL let
  • 带 cookie 的 Alamofire 请求

    我是初学者 我不知道如何使用 Alamofire 发出 GET 请求 但它需要身份验证 我设法用其他网络服务 登录 来做到这一点 因为它需要参数参数 parameters username username password passwor
  • 将Json字符串映射到java中的map或hashmap字段

    假设我从服务器返回了以下 JSON 字符串 response imageInstances one id 1 url ONE two id 2 url TWO 杰克逊代码大厦 JsonProperty 我怎样才能得到HashMap对象出来了
  • Perl:散列 2 中数组的数值排序(施瓦茨变换)

    这实际上是该线程的后续内容 Perl 散列中数组的数字排序 https stackoverflow com questions 7914931 perl numerical sort of arrays in a hash 我无法编辑原始问
  • Xcode 8.3 / Xcode 9.0 刷新配置文件设备

    我添加了一些新设备 当 Xcode 8 自动管理签名资产时 如何刷新配置文件 我发现了这个问题 刷新 Xcode 7 管理的团队配置文件中的设备 https stackoverflow com questions 32729193 refr

随机推荐