2012-12-05 88 views
0

我正在使用ZipArchive並正在從設備讀取數據。我想要做的是從設備中獲取數據並將其解壓縮。我能找到的唯一例子是將數據寫入iOS設備上的文件,然後再讀取(解壓縮)它...使用ZipArchive解壓縮NSData

這是我寫它的代碼(不工作)磁盤...

// Read the data in... 
if ((recvStringLen = recvfrom(connectSock, recvString, 1025, 0, (struct sockaddr *)&broadcastAddr, &recvStringLen)) < 0) { 
    NSLog(@"ERROR: Unable to receive user perms message."); 
    [self showTimeoutError]; 
    return -1; 
} 

// get the file size... 
unsigned int fileSize = ((recvString[16] << 24) & 0xff000000) | 
         ((recvString[17] << 16) & 0xff0000) | 
         ((recvString[18] << 8) & 0xff00) | 
         (recvString[19] & 0xff); 

NSLog(@"fileSize: %i", fileSize); 

recvString[20+fileSize] = '\0'; // terminate the string... 

// convert the char data to a string 
NSString *stringData = [[[NSString alloc] initWithFormat:@"%s", &recvString[20]] autorelease]; 
NSData *data = [[[NSData alloc] initWithBytes:stringData length:fileSize] autorelease]; 

// write the data... 
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"userinfo.zip"]; 
[data writeToFile:appFile atomically:YES]; 

// exist? 
BOOL zipExists = [[NSFileManager defaultManager] fileExistsAtPath:appFile]; 

NSString *zipFilePath = [documentsDirectory stringByAppendingPathComponent:@"userinfo.zip"]; 

NSString *output = [documentsDirectory stringByAppendingPathComponent:@"userinfo.dat"]; 

ZipArchive* za = [[ZipArchive alloc] init]; 

// unzip it... 
BOOL success = [za UnzipOpenFile:zipFilePath]; 
if(success) { 
    BOOL outSuccess = [za UnzipFileTo:output overWrite:YES]; 
    if(outSuccess != NO) { 
     NSLog(@"success"); 
    } 

    [za UnzipCloseFile]; 
} 

[za release]; 

BOOL datExists = [[NSFileManager defaultManager] fileExistsAtPath:output]; 

當它變成'成功'時,即使'zipExists'爲YES,它總是NO ...。

我有兩個問題: 1.我沒有成功地將數據寫入磁盤,讀取數據並解壓縮。 2.我寧願只是解壓縮,而不是去通將其寫入磁盤,並再次回讀數據(NSData的)...

我發佈前搜查,但未能找到一個解決方案...

回答

0

跳過創建NSString - 這是您的問題(或其中之一)。直接從recvString創建數據對象。想想如果數據有一個空字節,使用%s會發生什麼。

+0

謝謝。我做了改變...仍然不起作用。有沒有辦法解壓縮數據而不先寫入磁盤? – user1614833

相關問題