为日期大于日期的Socrate数据集查询构造URL

时间:2016-05-25 23:51:31

标签: swift soql socrata

这个问题已被提出,但在Swift环境中没有。我有一个Socrata数据集,我正在使用OS X Swift应用程序检索这样的查询:

https://data.cityofwestsacramento.org/resource/wdus-j2nt.json?$where=date_applied>=2016-05-01

问题似乎是“$ where = date_applied> = 2016-05-01”的编码,而且Socrata不喜欢明显编码的日期部分。

关于如何在Swift中构造NSURL以正确传递此查询的任何想法?

1 个答案:

答案 0 :(得分:1)

使用https://github.com/socrata/soda-swift中的代码找到解决方案。 licenseTimeFrame只是回顾的天数:

  let dateCuttoff = NSCalendar.currentCalendar().dateByAddingUnit(.Day, value: -licenseTimeFrame,toDate: NSDate(), options: NSCalendarOptions(rawValue: 0))
    let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
    let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: dateCuttoff!)
    let dateString = "\(components.year)" + "-" + "\(components.month)" + "-" + "\(components.day)"
    let query = "date_applied>'\(dateString)'"
    let sk = query.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! as String
    let url = "https://data.cityofwestsacramento.org/resource/wdus-j2nt.json?$where=\(sk)"
    let urlToSend = NSURL(string: url)
    let request = NSMutableURLRequest(URL: urlToSend!);
    request.addValue("application/json", forHTTPHeaderField:"Accept")
    request.HTTPMethod = "GET"
    request.addValue("[myapikey]", forHTTPHeaderField: "X-App-Token")
    // Execute HTTP Request
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in }
    // do processing here of return data
    task.resume()