【问题标题】:Can not show progress bar while uploading image to server上传图片到服务器时无法显示进度条
【发布时间】:2017-03-03 06:02:31
【问题描述】:

我迫切需要显示进度条或活动指示器,因为图片上传需要时间。下面是我的代码,我无法弄清楚为什么没有显示进度条。我用过 ProgressHUD。

 [ProgressHUD show:@"Please wait..."];
  NSDictionary *params =@{ @"name":self->Name.text, @"contact_no":self->ContactNo.text,@"email_id":self->EmailId.text,@"s_date":Date,@"s_time":Time,@"streat":Street,@"city":City,@"state":State};

 NSData *uploadData = Data;
 NSString *urlString = [NSString stringWithFormat:@"http://fsttest.com/iosservice/supremo/add_supremo"];


 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
 [request setURL:[NSURL URLWithString:urlString]];
 [request setHTTPMethod:@"POST"];

 NSString *boundary = @"---------------------------14737809831466499882746641449";
 NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
 [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
 NSString *kNewLine = @"\r\n";

 NSMutableData *body = [NSMutableData data];

 for (NSString *name in params.allKeys) {

    NSData *values = [[NSString stringWithFormat:@"%@", params[name]] dataUsingEncoding:NSUTF8StringEncoding];

    [body appendData:[[NSString stringWithFormat:@"--%@%@", boundary, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"", name] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithFormat:@"%@%@", kNewLine, kNewLine] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:values];
    [body appendData:[kNewLine dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file_name\"; filename=\"test\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:uploadData]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[request setHTTPBody:body];


NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

【问题讨论】:

  • sendSynchronousRequest 不显示进度条,如果要显示进度条,那就去sendASynchronousRequest
  • SynchronousRequest 不显示进度条。它适用于同一线程。使用不同的线程或使用异步请求。
  • @Anbu.Karthik 可以请给我相同的代码。
  • 您是否尝试使用 sendSynchronousRequest 在主线程本身上发送图像。这可能会阻止 hud 实际出现吗?
  • @Anbu.Karthik 是的,异步工作正常,谢谢 :)

标签: ios objective-c image-uploading


【解决方案1】:

选择 1

按照你的方式继续添加委托并检查

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

    float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
    float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
    NSLog(@"progress/total %f",progress/total);
}

选择 2

将您的请求从sendSynchronousRequest 修改为sendAsynchronousRequest,例如

 //  NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

像这样调用方法

// set URL
[request setURL:[NSURL URLWithString:baseUrl]];

// add your progress bar here
[ProgressHUD show:@"Please wait..."];

[NSURLConnection sendAsynchronousRequest:request
                               queue:[NSOperationQueue mainQueue]
                   completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

                       NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;

                        [ProgressHUD dismiss];

                       if ([httpResponse statusCode] == 200) {

                           NSLog(@"success");
                           if ([data length] > 0 && error == nil)
                               [delegate receivedData:data];
                               // hide the progress bar here
                       }

                   }];

【讨论】:

  • 但我不确定,如果你想显示每个时刻的进度,sendSynchronousRequest to sendAsynchronousRequest 没有帮助,在这里你需要去NSURL Connection with delegates
【解决方案2】:

您可以使用 AFNetworking 轻松上传图片。 here 点击 AFNeworking 下载。和你的代码上传图片一样。

-(void)imageUpload
{
    @try
    {
        [self progressViewDispaly];
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager.requestSerializer setTimeoutInterval:600.0];
        [manager POST:YOUR_WEB_SERVICE_NAME parameters:YOUR_REQUEST_PARA constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
         {
             for(NSString *strImageName in ImageArray) //if multiple images use image upload
             {
                 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                 NSString *documentsDirectory = [paths objectAtIndex:0];
                 NSString *path = [documentsDirectory stringByAppendingPathComponent:strImageName];
                 if (path != nil)
                 {
                     NSData *imageData = [NSData dataWithContentsOfFile:path];
                     [formData appendPartWithFileData:imageData name:[NSString stringWithFormat:@"job_files[]"] fileName:[NSString stringWithFormat:@"%@",[[strImageName componentsSeparatedByString:@"/"] lastObject]] mimeType:@"image/jpeg"];
                 }
                 else
                 {
                 }
             }

         } progress:^(NSProgress * _Nonnull uploadProgress)
         {             
             [self performSelectorInBackground:@selector(makeAnimation:) withObject:[NSString stringWithFormat:@"%f",uploadProgress.fractionCompleted]];

         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
         {
             [SVProgressHUD dismiss];
             [_progressView removeFromSuperview];

         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

         }];

    } @catch (NSException *exception)
    {
        NSLog(@"%@",exception.description);
    }
}
-(void)makeAnimation:(NSString *)str
{
    float uploadProgress = [str floatValue];
    [_progressView setProgress:uploadProgress];
}
-(void)progressViewDispaly
{
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];

    _progressView = [[UIProgressView alloc] init];//WithProgressViewStyle:UIProgressViewStyleBar];
    _progressView.frame = CGRectMake(0, 0, CGRectGetWidth(statusBar.frame),20);
    _progressView.backgroundColor = [UIColor blueColor];
    _progressView.progressTintColor = [UIColor whiteColor];
    [statusBar addSubview:_progressView];
}

【讨论】:

    猜你喜欢
    • 2014-02-09
    • 1970-01-01
    • 2016-01-14
    • 2012-05-24
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    • 2012-12-17
    相关资源
    最近更新 更多