Cocoa question - NSTask isn't working

853 views Asked by At

NSTask isn't working; I think it has to do with the arguments. Here is my code:

 - (IBAction)downloadFile:(id)sender {

    // allocate our stuff :D
    progressIndication = [[NSProgressIndicator alloc] init];
    NSTask *downloader = [[NSTask alloc] init];

    // set up the downloader task
    [downloader setLaunchPath:@"/usr/bin/curl"];
    [downloader setArguments:[NSArray arrayWithObject:[NSString stringWithFormat:@"-LO %@", downloadURL]]];

    // go to the Desktop!
    system("cd ~/Desktop");

    // start progress indicator
    [progressIndication startAnimation:self];

    // download!
    [downloader launch];

    // stop the progress indicator, everything is done! :D
    [progressIndication stopAnimation:self];



}

Thanks

1

There are 1 answers

4
Itai Ferber On

You really don't need to use curl to do this; just use NSData to accomplish the task much more easily:

NSData *data = [NSData dataWithContentsOfURL:downloadURL];
[data writeToFile:[[NSString stringWithFormat:@"~/Desktop/%@", [downloadURL lastPathComponent]] stringByExpandingTildeInPath] atomically:YES];

If you insist you need to use curl for this, you're going to have to fix your code, which doesn't work for several reasons. First and foremost, your arguments are wrong. You should have the following code:

[downloader setArguments:[NSArray arrayWithObjects:@"-L", @"-O", [downloadURL absoluteString], @"-o", [NSString stringWithFormat:@"~/Desktop/%@", [downloadURL lastPathComponent]], nil];

Second, system("cd ~/Desktop") is meaningless; get rid of it.
Lastly, NSTask runs concurrently. [downloader launch] starts the operation, and your code continues. It should be:

[downloader launch];
[downloader waitUntilExit]; // block until download completes
[progressIndication stopAnimation:self];