[英]How to get Upload time remaining from Asynchronous Request?
我正在尝试将图像从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]);
}];
那么,如何计算剩余时间,以便可以显示指标? 谢谢你的时间。
您可以使用这种连接委托方法:
- (void) connection:(NSURLConnection *)connection
didSendBodyData:(NSInteger)bytesWritten
totalBytesWritten:(NSInteger)totalBytesWritten
totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite;
(我应该如何包装这么长的参数名称?)
它不在NSURLConnectionDataDelegate
文档中,但是如果您检查公共标头NSURLConnection.h
,它将在那里。 因此,不必担心使用它。
从文档URL加载系统编程指南 > 使用NSURLConnection :
估算上传进度
您可以使用
connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:
委托方法估算HTTP POST上传的进度。 请注意,这并不是对上传进度的精确度量,因为连接可能会失败或连接可能会遇到身份验证挑战。
我相信您希望显示类似进度条的内容。 我推荐使用MKNetworkKit,它为您提供了许多用于网络管理的工具,例如异步连接的进度。 检查此链接 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.