2012-10-02 34 views
5

我需要使用RubyMotion下載和解壓縮文件。我試着尋找例子,但找不到這個過程。Rubymotion:在iOS中下載和解壓ZIP文件

我有一個變量(@file),它是請求中的所有數據。我需要將這些數據寫入文件,然後解壓縮,保留未壓縮的數據並刪除tmp壓縮文件。

這是我到目前爲止有:

class LoadResourcesViewController < UIViewController 


    def viewDidAppear(animated) 
    @loading_bar = retrieve_subview_with_tag(self, 1) 
    req=NSURLRequest.requestWithURL(NSURL.URLWithString("#{someurl}")) 
    @connection = NSURLConnection.alloc.initWithRequest req, delegate: self, startImmediately: true 
    end 

    def connection(connection, didFailWithError:error) 
    p error 
    end 

    def connection(connection, didReceiveResponse:response) 
    @file = NSMutableData.data 
    @response = response 
    @download_size = response.expectedContentLength 
    end 

    def connection(connection, didReceiveData:data) 
    @file.appendData data 
    @loading_bar.setProgress(@file.length.to_f/@download_size.to_f) 
    end 

    def connectionDidFinishLoading(connection)  
    #create tmp file 
    #uncompress .tar, .tar.gz or .zip 
    #presist uncompresssed files and delete original tmp file 

    puts @file.inspect 
    @connection.release 
    solutionStoryboard = UIStoryboard.storyboardWithName("Master", bundle:nil) 
    myVC = solutionStoryboard.instantiateViewControllerWithIdentifier("Main3") 
    self.presentModalViewController(myVC, animated:true) 
    end 

end 

任何幫助或例子將是巨大的!

回答

3

所以我解決了這個解壓縮和untaring。

解壓:

#UNZIP given you have a var data that contains the zipped up data. 
tmpFilePath = "#{NSTemporaryDirectory()}temp.zip" #Get a temp dir and suggest the filename temp.zip 
@fileManager = NSFileManager.defaultManager() #Get a filemanager instance 
@fileManager.createFileAtPath(tmpFilePath, contents: data, attributes:nil) #Create the file in a temp directory with the data from the "data" var. 

destinationPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, true).objectAtIndex(0) //get the target home for the unzipped files. This MUST be within your domain in order to persist. 

SSZipArchive.unzipFileAtPath(tmpFilePath, toDestination: destinationPath) #Use the SSZipArchive to unzip the file. 
@fileManager.removeItemAtPath(tmpFilePath, error: nil) #Cleanup the tmp dir/files 

請記住,您必須包含SSZipArchive庫。我使用了obj-c庫而不是cocoapod。要做到這一點添加以下行您的Rake文件(假設你把OBJ-C文件中的供應商/ SSZipArchive文件夾):

app.libs += ['/usr/lib/libz.dylib'] 
app.vendor_project('vendor/SSZipArchive', :static) 

要解壓:

dir = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, true) #get target dir for untar'd files 
error_ptr = Pointer.new(:object) 
NSFileManager.defaultManager.createFilesAndDirectoriesAtPath(dir[0], withTarData: data, error: error_ptr) #Create and untar te data (assumes you have collected some tar'd data in the data var) 

在這種情況下,你需要Light Untar lib(https://github.com/mhausherr/Light-Untar-for-iOS/)。包括此LIB中添加以下到您的Rake文件(假設文件在供應商/解壓縮):

app.vendor_project('vendor', :static, :headers_dir=>"unTar") 
+0

幫我解決了相關的問題,感謝張貼您的解決方案! – sbauch