Cocoa File Upload with Progress Bar

2019-05-28 23:37发布

问题:

(This is really a double-whammy in terms of questions, since there really is two serperate questions, but they kinda belong together.)

First Question:

How would I go about uploading a file (I have an NSData object containing the file's contents already) using POST, while displaying the upload progress in an NSProgressIndicator? Much like one can do bytesReceived in NSURLDownload, but this time tracking how many bytes have already been sent using POST.

Second Question:

While I have this NSData Array, I shall be using the code below to send the NSData array. Here, it confuses me how I would tell it that for example, the POST value 'file' is the NSData object. NSDictionary would probably do the job here, but I don't have access to my computer and the lovely Apple Docs right now.:

NSMutableURLRequest* post = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:@"http://yourdomain.com/post.php"]];

[post setHTTPMethod: @"POST"];

[post setHTTPBody:myFileNSData];

NSURLResponse* response;

NSError* error;

NSData* result = [NSURLConnection sendSynchronousRequest:post returningResponse:&response error:&error];

NSLog(@"%@", [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease]);

I'd appreciate any help.

回答1:

NOTE - unfortunately this post is of only historic interest as, sadly, ASIHttpRequest stopped development after some years. A tragedy for the community.

The best answer today (2014) is: "simply, you must use one of the libraries available to do this."

It would be, literally, crazy to "roll your own" when there are perfect libraries out there, with literally 10+ man-years of development behind them. So, find a library (sadly not ASIHttpRequest any more!) Hope it helps!


Simply use ASIHttpRequest. It's the most-used library in all of iOS and the usual networking library on Mac.

Progress tracking is built-in. It is utterly trivial to use.

Don't forget to make a small donation to the guy if you can - if he stops developing it we're all stuffed!



回答2:

If you want to use just Cocoa to do this (and I agree that ASIHTTPRequest is excellent), you'll need to do the post asynchronously. The example code you've posted here is synchronous.

This just means that you'll need to implement some of the delegate methods of NSURLConnection to handle information about how your upload is progessing. In particular, implementing the method connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite: will enable you to update on progress in your UI.