0

I'm trying to use webapi in my code. my JSON service has odata filtering. But when I try to send my link into my JSON serializer, I get "nil" response at myURL2. But if I send without parameter it works fine. Do you have any suggestions? How can I use ODATA in my code?

        let link = "https://apiservices.domain.com/api/Events?$filter=EventDate gt datetime'2018-02-01' and EventDate lt datetime'2018-02-15'"

        let myURL2 = NSURL(string: link)
        let request2 = NSMutableURLRequest(url: myURL2 as! URL)
        request2.httpMethod = "GET"


        request2.addValue("Bearer "+tokenNewId, forHTTPHeaderField: "Authorization")
        request2.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "content-type")
        request2.setValue("application/json", forHTTPHeaderField: "Accept")

        let task2 = URLSession.shared.dataTask(with: request2 as URLRequest) {(data2, response2, error2) -> Void in
            if let unwrappedData2 = data2 {
                do {
                    guard let records = try? JSONSerialization.jsonObject(with: unwrappedData2, options: .mutableContainers) as? [[String: Any]] else {
                        return
                    }
           }
4
  • ...$filter=EventDate gt datetime'2... The spaces may cause the issue. Could you check url then? Commented Feb 23, 2018 at 13:04
  • when i execute this link at postman, i get response Commented Feb 23, 2018 at 13:09
  • My bad, wasn't explicit, could you check the value of myURL2 then? Commented Feb 23, 2018 at 13:10
  • Postman must percent-escape the URL before sending it. Spaces are most definitely not legal in URLs. Commented Feb 23, 2018 at 13:33

2 Answers 2

1

Try this:

let urlwithPercentEscapes = link.addingPercentEncoding( 
withAllowedCharacters: .urlQueryAllowed)
let myURL2 = NSURL(string: urlwithPercentEscapes!)
Sign up to request clarification or add additional context in comments.

1 Comment

Spaces are not legal in URLs. Since your URL contains spaces, each space character must be escaped as %20. That's what this answer does, and why it work.
1

I believe that your problem is that your url is not percent-encoded. You need to use the stringByAddingPercentEncodingWithAllowedCharacters: method to do that.

Here is a post that shows you how to do it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.