2017-07-19 20 views
2

curl -o http://example.com/file.zipをObjective Cアプリケーションで実行したいとします。コマンドが実行されている間に更新されるダウンロードステータスを含むラベルまたはテキストボックスを表示したいとします。おそらく、これはdispatch_asyncを使用して達成することができましたが、今はどうしたらよいのでしょうか。重複としてマーキングする前に、私が見つけたメソッドは、コマンドを実行し、の後にの出力が完了しました。私はそれが実行中の出力を取得したい、ちょっと端末エミュレータのように。Objective cでshellコマンドを実行して同時に出力を取得する

答えて

2

あなたがstandardOutputプロパティを使用してNSTaskからNSPipeを接続し、データ使用可能通知を受け取るために登録する必要があります。

@interface TaskMonitor: NSObject 
@property NSPipe *outputPipe; 
@end 

@implementation TaskMonitor 

-(void)captureStandardOutput:(NSTask *)process { 

    self.outputPipe = [NSPipe new]; 
    process.standardOutput = self.outputPipe; 

    //listen for data available 
    [self.outputPipe.fileHandleForReading waitForDataInBackgroundAndNotify]; 

    [[NSNotificationCenter defaultCenter] addObserverForName:NSFileHandleDataAvailableNotification object:self.outputPipe.fileHandleForReading queue:nil usingBlock:^(NSNotification * _Nonnull note) { 

    NSData *output = self.outputPipe.fileHandleForReading.availableData; 
    NSString *outputString = [[NSString alloc] initWithData:output encoding:NSUTF8StringEncoding]; 

    dispatch_async(dispatch_get_main_queue(), ^{ 
     // do something with the string chunk that has been received 
     NSLog(@"-> %@",outputString); 
    }); 

    //listen again... 
    [self.outputPipe.fileHandleForReading waitForDataInBackgroundAndNotify]; 

    }]; 

} 

@end 
+0

こんにちは私はこれを試しましたが、問題があります。それはコマンド全体を実行し、出力はNSLoggedを取得します。NSTaskで正常に実行されるように出力され、*の後ろには、その後のデータなしでログに無限の ' - >'を付けます。この ' - ><!DOCTYPE html>'です。私が言ったように、すべてのデータに対して1つの ' - >'が必要なので、実際にUIを更新することができます。 –

+0

何らかの理由でNvmがログ上で動作していませんでしたが、UIに接続したときに機能しました! –

関連する問題