-1

I am still learning the programming in Swift, I have successfully consumed services with Alamofire, but now I face the following problem, I have a service where I sent 2 json in the URL and I really have no idea how to send this data, I have seen some examples but I still can not understand. Already configure the security policy however the problem is the same

This is my URL {{url}}apps/Search2/{"search":"","user":14,"category":2,"numero":0,"subgroup":-1,"tipo":-1,"subcategory":-1,"cantidad":0}/{"max":5000,"minimo":1}

and this is what I have been trying

static func loadMenuWithFilter(search : String, userId : Int, categoryId : Int ){
        let menu : Parameters  = ["search" : search, "user" : userId, "category" : categoryId, "numero" : 0, "subgroup" : -1, "tipo" : -1, "subcategory" : -1,"cantidad" : 0]
        Alamofire.request(AlamofireConstants.MENU_FILTER, method: .get, parameters: menu, encoding: JSONEncoding.default)
        .validate(statusCode: 200..<300).responseData { response in
            switch response.result {
            case .failure(let error):
                print("error ==> \(error)")
            case .success(let data):
                do{
                    let decoder = JSONDecoder()
                    decoder.keyDecodingStrategy = .convertFromSnakeCase
                    let result = try decoder.decode(Menu.self, from: data)
                    print("MenuController \(result)")

                } catch {
                    print("MenuController \(error)")
                }
            }
        }
    }

obviously I have not had successful because I'm sure it's not the right way to do it. My service response is 404

dbenitobaldeon
  • 324
  • 3
  • 20
  • What is the error you're getting? – onnoweb Jun 10 '19 at 18:29
  • This seems ok, but it really depends on what error are you getting. Because it can be number of things- bad url, incorrect method (post?), incorrect params key, server unavailable etc. – Lirik Jun 10 '19 at 18:47
  • @onnoweb I just updated my question with the error – dbenitobaldeon Jun 10 '19 at 20:06
  • @Lirik I just updated my question with the error – dbenitobaldeon Jun 10 '19 at 20:07
  • 2
    Possible duplicate of [The resource could not be loaded because the App Transport Security policy requires the use of a secure connection](https://stackoverflow.com/questions/32631184/the-resource-could-not-be-loaded-because-the-app-transport-security-policy-requi) – NSNoob Jun 10 '19 at 20:07
  • and btw, why are you appending a whole json in the URL? Seems...odd. It is often seen with GET requests where you append one parameter or two in the URL but if you want to send a whole json object, you append it in the request body. – NSNoob Jun 10 '19 at 20:09
  • Definitively a duplicate. OP: You need to use `https` and read up about `App Transport Security`. A quick search of the error itself reveals plenty of posts and resources to help you solve the problem. And a good way to learn is to learn how to search for errors (search for the actual message, not the whole copypasta) – Claus Jørgensen Jun 10 '19 at 20:10
  • good the web service works that way @NSNoob – dbenitobaldeon Jun 10 '19 at 20:10
  • @NSNoob Including a body on a GET request is not supported. – onnoweb Jun 10 '19 at 20:12
  • which part did not read well that I'm still learning swift, your comments only make my publication lessens its impact. Anyway, thank you for providing the information that will be useful to me but you should read well and have consideration for what we still learn and that is precisely why there is a page like this partner. @ClausJørgensen – dbenitobaldeon Jun 10 '19 at 20:14
  • @onnoweb so how do I send a leather json with alamofire? I think that would solve the problem with that. – dbenitobaldeon Jun 10 '19 at 20:16
  • @dbenitobaldeon learning is not an excuse for not doing a search before asking a question. You could literally paste your error into Google and get an exact answer to your problem. You showed absolutely zero effort at solving this yourself prior to asking. – Claus Jørgensen Jun 10 '19 at 20:16
  • As I told you, read the publication better please, I mention that I have seen many examples among which the link that you passed to me is included but what I am looking for is for someone to explain to me because he gives that error or how to do it correctly because with the examples It is not very clear. Partner you must read well please to avoid these inconveniences and negative comments. @ClausJørgensen – dbenitobaldeon Jun 10 '19 at 20:19
  • 1
    @onnoweb I thought POST would be obvious. The comment wouldn't let me edit it now. – NSNoob Jun 10 '19 at 20:21
  • @OP: If you must append it in the url, [convert it into a string and then append it to the url](https://stackoverflow.com/questions/39018192/sending-json-object-in-get-request-in-swift-in-alamofire). Otherwise make it a POST request and use ObjectMapper or whatever your prefer to create your json and add it to to body – NSNoob Jun 10 '19 at 20:22
  • @onnoweb It is definitely possible to send query params in the url .Alamofire takes care of this when you send the params as a hash, which he did. So a GET can be used here. – Lirik Jun 10 '19 at 20:41
  • The problem here as mentioned above - `App Transport Security policy`. You are trying to access an HTTP url, and not HTTPS, and that is not allowed unless you specify this in the info.plist. @dbenitobaldeon – Lirik Jun 10 '19 at 20:44
  • 1
    @Lirik Indeed. I was talking about sending a body along in a GET request. That is not supported. – onnoweb Jun 10 '19 at 21:21
  • @Lirik I no longer get the same error but now I get a 404 – dbenitobaldeon Jun 10 '19 at 22:04
  • @dbenitobaldeon 404 usually means the url you're trying to access is not found. A good test will be putting the url in a browser (append the query params yourself) and see what happens – Lirik Jun 11 '19 at 13:13
  • hat's the weird thing, because from the web and POSTMAN everything works ok! it seems to me that json data is not body if it should not go in the same URL @Lirik – dbenitobaldeon Jun 11 '19 at 14:23
  • @dbenitobaldeon If it works on web, there's no reason it won't work on iOS. check the params you are sending are the same. Check the request headers (content-type etc.) Also, fix the url in the question, It should be: {{url}}/apps/Search2?search=something&user=14&category=2&numero=0&subgroup=-1&tipo=-1&subcategory=-1&cantidad=0&max=5000&minimo=1 (btw, why is the search term empty? this can also be a problem) – Lirik Jun 11 '19 at 14:51

2 Answers2

0

After looking for, several post I found the solution to my problem, as I mentioned what I needed was to send a json in my URL chain, it should be noted that they were not parameters, even until now I do not understand why my question was marked as duplicate. But the solution was to convert my variable menu that was of type Parameter, transform it to a string and then simply concatenate it with the URL. With this action the service was successfully executed, it was not necessary to perform all the settings that I indicated in the comments, nor the configuration in the App Transport Security and not passing my varible menu as Encoding.default. None of this worked.

This was simply done

ConvertJson.jsonToString(json: menu as AnyObject)


class func jsonToString(json: AnyObject) -> String{
        var item : String!
        do {
            let data1 =  try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // first of all convert json to the data
            let convertedString = String(data: data1, encoding: String.Encoding.utf8) // the data will be converted to the string
            item = convertedString!
        } catch let myJSONError {
            print(myJSONError)
        }
        return item
    }

I got the example code from this link where they have a similar problem

dbenitobaldeon
  • 324
  • 3
  • 20
-1

Try changing JSONEncoding.default to URLEncoding.default?