2013年9月4日 星期三

遠端更新福音!ZIP Support in Corona

解壓後小心水母和鱷魚!
有段時間在思考一件事情

是不是每次更新都要很麻煩的上架一次新版本

七天以上的APPLE 審核速度 OMG

如果我有不少圖片,文字需要讓使用者更新

那不是很麻煩嗎,放在網路空間就好幾十個檔

其實有一個更方便的方法,自從Corona 支援Plugin 後不久

ZIP 的Plugin 就出現了!!

沒錯,壓縮,解壓縮的好幫手,相信你已經想到很多應用的方法了吧!?

讓我們趕快來看看怎麼使用吧。

plugins =
{
-- zip plugin
["plugin.zip"] =
{
publisherId = "com.coronalabs",
},
},
view raw build.settings hosted with ❤ by GitHub
build.settings加上這段後,第一次編譯會從Corona Server端取得此Plugin元件

之後就可以很順𣈱的使用ZIP

接下來小島來介紹一下怎麼從網路端下載ZIP並放在屬意的資料夾內供之後使用

重點如下
  • 使用network.download 從網路上下載檔案
  • 利用networkListener,判斷下載完成後將該檔案利用zip解壓縮
  • 接著接壓縮完成後呼叫zipListener,在這裡就可以告訴使用者,更新完成謝謝等候囉!

local zip = require( "plugin.zip" ) -- 呼應build.settings裡的["plugin.zip"]
local function zipListener( event ) -- 解壓縮完成後呼叫此處
if ( event.isError ) then -- 若解壓有錯誤會跑至此處
print( "Unzip error" )
else
print( "event.name:" .. event.name ) -- event.name:zip
print( "event.type:" .. event.type ) -- event.type:uncompress
if ( event.response and type(event.response) == "table" ) then -- 這裡會印出所有在ZIP檔的檔名
for i = 1, #event.response do
print( event.response[i] )
end
end
end
end
local function networkListener( event ) -- 判斷ZIP下載成功或失敗
if ( event.isError ) then
print( "Network error - download failed" )
elseif ( event.phase == "began" ) then
print( "Progress Phase: began" )
elseif ( event.phase == "progress" ) then -- 當progress 設為download 時,下載階段將會回傳下載進度,讓使用者能知道進度
if event.bytesEstimated <= 0 then
print( "Download progress: " .. event.bytesTransferred )
else
print( "Download progress: " .. event.bytesTransferred .. " of estimated: " .. event.bytesEstimated )
end
elseif ( event.phase == "ended" ) then
if ( math.floor(event.status/100) > 3 ) then
--會得到一個網路的status code,3xx以上的代表下載失敗
--404代表找不到檔案
print( "Network error - download failed", event.status )
else -- 成功的話跑這裡
local options = { -- 設置壓縮或解壓的參數
zipFile = event.response.filename, -- 在這裡filename會是test.zip
zipBaseDir = event.response.baseDirectory, -- zip檔所在位置
dstBaseDir = system.DocumentsDirectory, -- 解壓縮後目標位置
listener = zipListener,
}
zip.uncompress( options ) -- 完成後會呼叫zipListener
end
end
end
local params = {}
params.progress = "download" -- 設progress 為"download"就會回傳下載進度喔!!
local URL = "http://coronaisland.s3.amazonaws.com/coronabook/coronaisland_ziptest.zip"
network.download( URL, "GET", networkListener, params, "test.zip", system.TemporaryDirectory ) -- 預設一個下載檔名後放在暫存資料夾來作處理
view raw main.lua hosted with ❤ by GitHub
小島在ZIP中放了兩個檔案,跑完此段程式碼應該可以在DocumentsDirectory看到兩張圖片,恭禧您!這樣就完成囉!將其應用在APP的更新上吧!配合JSON來判斷將更無往不利喔!

沒有留言:

張貼留言