0

This is the result that I want

func getOffers(_ page: Int, _ i: Int) {
    getOfferProducts(category: [""], sort: -1, page: page) { (products) in

        let keyboard = [ "inline_keyboard" : [
                                [
                                    ["text" : "Amazon", "url" : products[i].detailedPageURL]
                                ]
                            ]
                        ]

        var url = "https://api.telegram.org/bot" + apiToken + "/sendPhoto?" +
            "chat_id=" + chatId +
            "&caption=" + products[i].title + "\n\n" +
            "Prezzo iniziale: " + String(products[i].startingPrice) + " €\n" +
            "Prezzo attuale: " + String(products[i].price) + " €\n" +
            "Risparmi il " + String(Double(products[i].percentOff!)) + "%\n\n" +
            "►" + String(products[i].detailedPageURL) +
            "&photo=" + String(products[i].largeImageURL!) +
            "&reply_markup=" + keyboard

        DispatchQueue.main.async {
            let url = URL(string: url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")
            let downloadTask = URLSession.shared.dataTask(with: url!) { (data : Data?, response : URLResponse?, error : Error?) in
                // Do what you want with data
            }
            downloadTask.resume()
        }

    }
}

If I don't include the parameter "reply_markup" it works (without the button obviously). Instead if I try to add a button it return the error:

{"ok":false,"error_code":400,"description":"Bad Request: can't parse reply keyboard markup JSON object"}

Paolo Luchini
  • 81
  • 1
  • 6

1 Answers1

0

According with this solution, reply_markup needs to be converted as a JSON encoded object before sending to the API.

So, this would solve your problem:

    let keyboard = [ "inline_keyboard" : [
                    [
                        ["text" : "Amazon", "url" : products[i].detailedPageURL]
                    ]
                   ]]

    guard let keyboardData = try? JSONSerialization.data(withJSONObject: keyboard, options: []) else {
        return
   }

    var url = "https://api.telegram.org/bot" + apiToken + "/sendPhoto?" +
        "chat_id=" + chatId +
        "&caption=" + products[i].title + "\n\n" +
        "Prezzo iniziale: " + String(products[i].startingPrice) + " €\n" +
        "Prezzo attuale: " + String(products[i].price) + " €\n" +
        "Risparmi il " + String(Double(products[i].percentOff!)) + "%\n\n" +
        "►" + String(products[i].detailedPageURL) +
        "&photo=" + String(products[i].largeImageURL!) +
        "&reply_markup=" + String(data: keyboardData, encoding: String.Encoding.utf8)!
alxlives
  • 5,084
  • 4
  • 28
  • 50