1

我正在尝试将图像从 iPhone 上传到服务器。我能够这样做但我需要显示一个指标。我的代码是

NSData *imageData = UIImageJPEGRepresentation(newImage, 90);

// setting up the URL to post to
NSString *urlString = [NSString stringWithFormat:@"URL",[[formater stringFromDate:now] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
// setting up the request object now
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
  NSString *boundary = [NSString stringWithFormat:@"---------------------------14737809831466499882746641449"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
 NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image\"; filename=\"ipodfile.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];

这是触发请求的代码。

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               NSLog(@"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
 }];

那么如何计算剩余时间以便显示指标?谢谢你的时间。

4

2 回答 2

4

您可以使用这种连接委托的方法:

- (void)       connection:(NSURLConnection *)connection
          didSendBodyData:(NSInteger)bytesWritten
        totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite;

(我应该如何包装这么长的参数名称?)
它不在文档中NSURLConnectionDataDelegate,但是如果您检查 public header NSURLConnection.h,它就在那里。所以不用担心使用它。

从文档URL Loading System Programming Guide > Using NSURLConnection

估计上传进度

connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:您可以使用委托方法估计 HTTP POST 上传的进度。请注意,这不是对上传进度的精确测量,因为连接可能会失败或连接可能会遇到身份验证挑战。

于 2013-02-28T14:10:12.860 回答
1

我相信您想显示进度条之类的东西。我建议使用 MKNetworkKit,它为您提供了许多网络管理工具,例如异步连接的进度。检查此链接

于 2013-02-28T14:03:21.127 回答