Rubymotion: загрузка и извлечение zip-файла в iOS
-
12-12-2019 - |
Вопрос
Мне нужно скачать и распаять файл в Rubymotion.Я пытался искать примеры, но не смог найти какой-либо из этого процесса.
У меня есть переменная (@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
.
Любая помощь или примеры были бы здоровы!
Решение
Итак, я решил это для расстегивания и бездействия.
для распечатки:
#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 lib.Я использовал Obj-C lib вместо какоапода.Для этого добавьте следующие строки в вашем RakeFile (предполагается, что вы поместите файлы OBJ-C в папку Vendor / 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)
.
В этом случае вам понадобится свет UNTER Lib (https://github.com/mhausherr/light-undar-fortios/).Чтобы включить это lib в добавлении следующего в свой RakeFile (предполагает, что файлы находятся на поставщике / нет):
app.vendor_project('vendor', :static, :headers_dir=>"unTar")
.