0

I am trying to parse JSON, everything works fine, but when I try to give a filter with the url, it says found nil while unwrapping an optional value. I was wondering if I should give the filters in some other way. PS.. The url works fine when I use it in the browser

this is how the url with filter looks like:

https://start.jamespro.nl/v4/api/json/tasks/?filter=[{"column":"Date","operator":"=","value":"2017-08-04"}, {"column":"UserId","operator":"=","value":"2"}]

and this is my whole code:

func apiRequestTasks(url: String) {
        apiRequestHeader(userName: "*******", passWord: "******")
        var running = false
        let urlProjects = NSURL(string: url)
        let task = session?.dataTask(with: urlProjects! as URL) {
            ( data, response, error) in
            if let taskHeader = response as? HTTPURLResponse {
                print(taskHeader.statusCode)
            }
            if error != nil {
                print("There is an error!!!")
                print(error ?? "")
            } else {
                if let content = data {
                    do {
                        let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
                        print(dictionary)

                    }
                    catch {
                        print("Error: Could not get any data")
                    }
                }
            }
            running = false
        }


        running = true
        task?.resume()

        while running {
            print("waiting...")
            sleep(1)
        }

    }
  • take the values of the filters and add them as parameters in the request – sarosh mirza Aug 04 '17 at 13:53
  • 1
    At least you have to percent encode the space characters, but does the URL really contain a full-fledged JSON string as parameter? That's hilarious. – vadian Aug 04 '17 at 13:54
  • @saroshmirza could you maybe give me an example of that? –  Aug 04 '17 at 13:54

2 Answers2

0

I think the problem is the way you create your URL, try something like this:

let filters = "[\"column\":\"Date\",\"operator\":\"=\",\"value\":\"2017-08-04\"}, {\"column\":\"UserId\",\"operator\":\"=\",\"value\":\"2\"}]"


if var url = URLComponents(string: "https://start.jamespro.nl/v4/api/json/tasks") {
    url.query = "filter=:\(filters)"
    print ("url", url.string ? "invalid url")
}
Sébastien REMY
  • 2,399
  • 21
  • 39
0

I just encoded the filter part of my url and it worked. But thanx for the reactions !!!

let filter = "[{\"column\":\"Date\",\"operator\":\"=\",\"value\":\"2017-08-04\"}, {\"column\":\"UserId\",\"operator\":\"=\",\"value\":\"2\"}]"
        let encodedFilter = filter.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
        let baseUrl = "https://start.jamespro.nl/v4/api/json/tasks/?filter="
        let url = baseUrl + encodedFilter!
        apiRequestTasks(url: url)