简体   繁体   中英

Update a network request in Corona SDK

I am fetching some json stuff(value of bitcoin) from a website with the network.request-function. However, I want that json stuff(value of bitcoin) to update to the latest version every time the user presses update. How would that be possible?

local json = require("json")
btcPriceText = display.newText("price", 50,100, "Arial", 25)

local function btcValue(event)
btcValue = json.decode(event.response)
dollarbtc= btcValue[1]['rate']
end

local function update()
if(dollarbtc) then
    btcPriceText.text = "BTC"..dollarbtc
end
end


network.request( "https://bitpay.com/api/rates", "GET", btcValue )
Runtime:addEventListener( "enterFrame", update )

This is all the code I'm using.

Referring to the excellent Corona docs on buttons page, you would put your network.request in the handleButtonEvent of the first example on that page. This way, every time the user clicks button, a new request is made. As soon as response arrives, the btcValue function will get called, thus setting the dollarbtc value based on the content of the response. Currently your update callback checks at every time frame whether the response data is available. So at very least, you should unset dollarbtc (set it to nil) after you update the text widget, otherwise you will be updating the widget at every time frame!

local function update()
    if (dollarbtc) then
        btcPriceText.text = "BTC"..dollarbtc
        dollarbtc = nil -- do come here again, text field updated!
    end
end

However, you don't even need to do that: update the text field when handling the response:

local function btcValue(event)
    local btcValue = json.decode(event.response)
    local dollarbtc= btcValue[1]['rate']
    btcPriceText.text = "BTC"..dollarbtc
end

and you can forget about the Runtime:addEventListener( "enterFrame", update ) line, no longer needed.

Don't forget to add a display.yourButton:addEventListener( "tap", handleButtonEvent) so the button responds to clicks . The tap event does not have phases (whereas the touch event does).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM