Search code examples
iosjsonswiftnsmutableurlrequesturlsession

sending parameters with json in swift


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

Solution

  • Try this:

    let urlwithPercentEscapes = link.addingPercentEncoding( 
    withAllowedCharacters: .urlQueryAllowed)
    let myURL2 = NSURL(string: urlwithPercentEscapes!)