如何为此 Web 服务调用 API 以在 swift 中分别获取当前和不存在日期的数组? [英] How to make API call for this web service to fetch array of present and absent dates separately in swift?

查看:14
本文介绍了如何为此 Web 服务调用 API 以在 swift 中分别获取当前和不存在日期的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前的问题是使用 2 个当前和缺席天数的数组在 FSCalendar 上简单地显示静态数据.

错误日志:

2017-06-17 10:23:50.671 ezSchool[1848:24475] -[UICachedDeviceWhiteColor unsignedLongLongValue]:无法识别的选择器发送到实例 0x608000059ec02017-06-17 10:23:50.672 ezSchool[1848:24475] 未能在(FSCalendar)上设置(placeholderType)用户定义的检查属性:-[UICachedDeviceWhiteColor unsignedLongLongValue]:无法识别的选择器发送到实例 0x608000059ec2017-06-17 10:23:50.672 ezSchool[1848:24475] -[UICachedDeviceWhiteColor unsignedLongLongValue]:无法识别的选择器发送到实例 0x608000059ec02017-06-17 10:23:50.672 ezSchool[1848:24475] 未能在(FSCalendar)上设置(firstWeekday)用户定义的检查属性:-[UICachedDeviceWhiteColor unsignedLongLongValue]:无法识别的选择器发送到实例 0x6080000592017-06-17 10:23:50.672 ezSchool[1848:24475] -[UICachedDeviceWhiteColor doubleValue]:无法识别的选择器发送到实例 0x608000059ec02017-06-17 10:23:50.673 ezSchool[1848:24475] 未能在(FSCalendar)上设置(headerHeight)用户定义的检查属性:-[UICachedDeviceWhiteColor doubleValue]:无法识别的选择器发送到实例 0x608000059ec02017-06-17 10:23:50.673 ezSchool[1848:24475] -[UICachedDeviceWhiteColor doubleValue]:无法识别的选择器发送到实例 0x608000059ec02017-06-17 10:23:50.673 ezSchool[1848:24475] 无法在(FSCalendar)上设置(headerTitleTextSize)用户定义的检查属性:-[UICachedDeviceWhiteColor doubleValue]:无法识别的选择器发送到实例 0x608000059ec0错误:可选(错误域=NSURLErrorDomain 代码=-1002 不支持的 URL" UserInfo={NSUnderlyingError=0x60000005cbc0 {错误域=kCFErrorDomainCFNetwork 代码=-1002 (空)"},NSErrorFailingURLStringKey=ezschoolportalapi.azureportalapinet/api/Students.AttendanceDetails?schoolid=1&studentid=2&month=6&year=2017, NSErrorFailingURLKey=ezschoolportalapi.azurewebsites.net/api/Student/AttendanceDetails?schoolid=1&studentid=2&month=6&year=2017, NSLocalizedDescription=不受支持的网址})

解决方案

不要在 Swift 中使用 NSDictionary,你只需要使用 DateFormatter 来获取你的格式化日期.同样正确的 JSON 字典在 Swift 3 中是 [String:Any].

首先在你的 [String] 类型的类中声明两个名为 presentDateArrayabsentDateArray 的实例属性.

var presentDateArray = [String]()var 缺席日期数组 = [String]()

现在以这种方式在响应完成块中初始化这两个数组.

if let responseJSON = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)) as?[字符串:任何],让presentdetails = responseJSON["Present"] as?[[字符串:任何]],让 Absentdetails = responseJSON["Absent"] 作为?[[字符串:任何]] {让 dateFormatter = DateFormatter()dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"self.presentDateArray = presentdetails.flatMap { dateFormatter.date(for: $0["Date"] as!String) }.flatMap { dateFormatter1.string(from:$0) }self.absentDateArray = Absentdetails.flatMap { dateFormatter.date(for: $0["Date"] as!String) }.flatMap { dateFormatter1.string(from:$0) }DispatchQueue.main.async {日历.reloadData()}}

现在只需在您的

方法委托中使用这两个数组

func calendar(_ calendar: FSCalendar, Appearance: FSCalendarAppearance, titleDefaultColorFor date: Date) ->用户界面颜色?{让 datestring2 : String = dateFormatter1.string(from:date)如果presentDateArray.contains(datestring2) {返回 UIColor.green}否则如果 presentDateArray.contains(datestring2) {返回 UIColor.red}别的 {返回零}}

it was my previous question to simply display static data on FSCalendar using 2 arrays of present and absent days.

How to change background color of events array in FSCalendar swift 3?

now I want to fetch the present and absent dates from the following json response in the format of 2array named : present and absent want to display on FSCalendar according to my previous question.

How to parse the same?. Please guide me. Thanks in advance.

{
  "Present": [
  {
  "Student_ID": 2,
  "LeaveLetterApplied": null,
  "Message": null,
  "Date": "2017-06-04T00:00:00",
  "Notify": null,
  "Status": "Present"
 },
 {
  "Student_ID": 2,
  "LeaveLetterApplied": null,
  "Message": null,
  "Date": "2017-06-05T00:00:00",
  "Notify": null,
  "Status": "Present"
}],
  "Absent": [
   {
     "Student_ID": 2,
     "LeaveLetterApplied": "",
     "Message": "",
     "Date": "2017-06-01T00:00:00",
     "Notify": null,
     "Status": "Absent"
   },
   {
     "Student_ID": 2,
     "LeaveLetterApplied": "",
     "Message": "",
     "Date": "2017-06-02T00:00:00",
     "Notify": null,
     "Status": "Absent"
   },
  {
     "Student_ID": 2,
     "LeaveLetterApplied": "",
     "Message": "",
     "Date": "2017-06-03T00:00:00",
     "Notify": null,
     "Status": "Absent"
  },
  {
    "Student_ID": 2,
    "LeaveLetterApplied": "Applied",
    "Message": "Sick Leave",
    "Date": "2017-06-06T00:00:00",
    "Notify": null,
    "Status": "Absent"
 }
],
   "No_Of_Working_Days": 6,
   "No_Of_Present_Days": 2,
   "Percentage": 0
 }

Below is the code m using to parse :

func getdateFromJSON()
{
    let url = NSURL(string: "http://ezschoolportalapi.azurewebsites.net/api/Student/AttendanceDetails?schoolid=1&studentid=1&month=1&year=2017")
    let request = NSMutableURLRequest(url: url! as URL)
    let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error)
        in
        guard error == nil && data != nil else
        {
            print("Error:",error)
            return
        }
        let httpstatus = response as? HTTPURLResponse
        if httpstatus?.statusCode == 200
        {
            if data?.count != 0
            {
                let responseString = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSDictionary
                let presentdetails = responseString["Present"] as? [[String:AnyObject]]
                let absentdetails = responseString["Absent"] as? [[String:AnyObject]]
                print(absentdetails)
                print(presentdetails)
               // dont know what to do next :(

                }

            else
            {
                print("No data got from URL")
            }
        }
        else{
            print("error httpstatus code is :",httpstatus?.statusCode)
        }

    }
    task.resume()

}

screenshot

Error Log :

2017-06-17 10:23:50.671 ezSchool[1848:24475] -[UICachedDeviceWhiteColor unsignedLongLongValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.672 ezSchool[1848:24475] Failed to set (placeholderType) user defined inspected property on (FSCalendar): -[UICachedDeviceWhiteColor unsignedLongLongValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.672 ezSchool[1848:24475] -[UICachedDeviceWhiteColor unsignedLongLongValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.672 ezSchool[1848:24475] Failed to set (firstWeekday) user defined inspected property on (FSCalendar): -[UICachedDeviceWhiteColor unsignedLongLongValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.672 ezSchool[1848:24475] -[UICachedDeviceWhiteColor doubleValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.673 ezSchool[1848:24475] Failed to set (headerHeight) user defined inspected property on (FSCalendar): -[UICachedDeviceWhiteColor doubleValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.673 ezSchool[1848:24475] -[UICachedDeviceWhiteColor doubleValue]: unrecognized selector sent to instance 0x608000059ec0 2017-06-17 10:23:50.673 ezSchool[1848:24475] Failed to set (headerTitleTextSize) user defined inspected property on (FSCalendar): -[UICachedDeviceWhiteColor doubleValue]: unrecognized selector sent to instance 0x608000059ec0 Error: Optional(Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x60000005cbc0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}, NSErrorFailingURLStringKey=ezschoolportalapi.azurewebsites.net/api/Student/AttendanceDetails?schoolid=1&studentid=2&month=6&year=2017, NSErrorFailingURLKey=ezschoolportalapi.azurewebsites.net/api/Student/AttendanceDetails?schoolid=1&studentid=2&month=6&year=2017, NSLocalizedDescription=unsupported URL})

解决方案

Don't use NSDictionary in Swift, you just need to use DateFormatter to get your formatted date. Also correct JSON dictionary in Swift 3 is [String:Any].

First of all declare two instance property in your class of type [String] named presentDateArray and absentDateArray.

var presentDateArray = [String]()
var absentDateArray = [String]()

Now initialize these two array in your response completion block this way.

if let responseJSON = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)) as? [String:Any],
    let presentdetails = responseJSON["Present"] as? [[String:Any]],
    let Absentdetails = responseJSON["Absent"] as? [[String:Any]] {

     let dateFormatter = DateFormatter() 
     dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
     self.presentDateArray = presentdetails.flatMap { dateFormatter.date(for: $0["Date"] as! String) }.flatMap { dateFormatter1.string(from:$0) }
     self.absentDateArray = Absentdetails.flatMap { dateFormatter.date(for: $0["Date"] as! String) }.flatMap { dateFormatter1.string(from:$0) }
     DispatchQueue.main.async {
         calendar.reloadData()
     }
}

Now simply use this two array in your delegate of method of

func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance,  titleDefaultColorFor date: Date) -> UIColor? {

    let datestring2 : String = dateFormatter1.string(from:date)

    if presentDateArray.contains(datestring2) {
        return UIColor.green
    }
    else if presentDateArray.contains(datestring2) {
       return UIColor.red
    }
    else {
       return nil
    }
}

这篇关于如何为此 Web 服务调用 API 以在 swift 中分别获取当前和不存在日期的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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