sending parameters with json in swift

710 Views Asked by At

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
                    }
           }
2

There are 2 best solutions below

1
Darkface35 On BEST ANSWER

Try this:

let urlwithPercentEscapes = link.addingPercentEncoding( 
withAllowedCharacters: .urlQueryAllowed)
let myURL2 = NSURL(string: urlwithPercentEscapes!)
0
Enrique Bermúdez On

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.