2013-07-22 52 views
2

任何機構都有關於在執行NSTask時從NSTask獲取通知的想法。我正在使用NSTask解壓zip文件,並且需要在NSProgressBar中顯示解壓數據進度。 我沒有發現任何想法做這樣的任務。所以我顯示值在進度條。 需要幫助來完成這項任務。 在此先感謝。從NSTask獲取任務進度的通知

回答

2

使用NSFileHandleReadCompletionNotification,NSTaskDidTerminateNotification通知。

task=[[NSTask alloc] init]; 

[task setLaunchPath:Path]; 

NSPipe *outputpipe=[[NSPipe alloc]init]; 

NSPipe *errorpipe=[[NSPipe alloc]init]; 

NSFileHandle *output,*error; 

[task setArguments: arguments]; 

[task setStandardOutput:outputpipe]; 

[task setStandardError:errorpipe]; 

output=[outputpipe fileHandleForReading]; 

error=[errorpipe fileHandleForReading]; 

[task launch]; 


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedData:) name: NSFileHandleReadCompletionNotification object:output]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedError:) name: NSFileHandleReadCompletionNotification object:error]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TaskCompletion:) name: NSTaskDidTerminateNotification object:task]; 

//[input writeData:[NSMutableData initWithString:@"test"]]; 
[output readInBackgroundAndNotify]; 

[error readInBackgroundAndNotify]; 


[task waitUntilExit]; 

[outputpipe release]; 

[errorpipe release]; 
[task release]; 
[pool release]; 


/* Called when there is some data in the output pipe */ 

-(void) receivedData:(NSNotification*) rec_not 

{ 

    NSData *dataOutput=[[rec_not userInfo] objectForKey:NSFileHandleNotificationDataItem]; 

    [[rec_not object] readInBackgroundAndNotify]; 

    [strfromdata release]; 

} 

/* Called when there is some data in the error pipe */ 

-(void) receivedError:(NSNotification*) rec_not 

{ 
    NSData *dataOutput=[[rec_not userInfo] objectForKey:NSFileHandleNotificationDataItem]; 

    if(!dataOutput) 

     NSLog(@">>>>>>>>>>>>>>Empty Data"); 

    [[rec_not object] readInBackgroundAndNotify]; 


} 

/* Called when the task is complete */ 

-(void) TaskCompletion :(NSNotification*) rec_not 

{ 

} 
+0

這些可以告訴你什麼時候解壓縮結束,但不會告訴你它有多遠。 –

+0

彼得對這些通知在流程完成時調用,而不是在流程執行時調用。 – Surjeet

2

爲了顯示進度,你需要找出兩兩件事:

  • 多少個文件中有存檔,或多少字節解壓縮後,他們將佔據完成
  • 您目前已解壓縮多少個文件或字節

您將通過讀取解壓縮任務的輸出找到這些文件或字節。 Parag Bafna的回答是一個開始;在receivedData:中,您需要解析輸出以確定剛發生的進展,然後將該進度添加到目前爲止的進度計數(例如,++_filesUnzippedSoFar)。

第一部分,找出工作的總大小,是棘手的。在運行解壓縮之前,您基本上需要運行解壓縮:第一個,-l(這是一個小寫的L),是列出壓縮文件的內容;第二個是解壓縮它。第一個,您讀取輸出以確定歸檔包含多少個文件/字節;第二個,您讀取輸出以確定提前進度條的值。

設置進度條的屬性是很簡單的部分;那些字面上只是doubleValuemaxValue。確定你在工作中的位置是困難的部分,並且是特定領域的 - 你需要閱讀解壓縮的輸出結果(兩次,以不同的形式),理解它告訴你什麼,並將其轉化爲進度信息。

NSTask中沒有任何東西可以幫助你。 NSTask的這部分內容始於standardOutput屬性。它不知道壓縮文件,檔案,檔案內容甚至是進度,因爲這些都不適用於大多數任務。這一切都是專門針對你的任務,這意味着必須寫代碼才能做到。

+0

第二個是問題。我們如何獲得,到目前爲止您已解壓縮多少個文件或字節,因爲完成任務後,NSTask方法waitUntilExit會返回我們的命令。 – Surjeet

+0

@Student:就像我說的,這不是NSTask的工作 - *你*需要閱讀和解析解壓縮的輸出。 –

+0

我可以解析unzip的輸出,但是可以解釋如何在執行過程中從NSTask獲取輸出嗎? – Surjeet