2017-03-03 100 views
1

由于图片上传需要时间,我非常需要显示进度条或活动指示器。下面是我的代码,我无法弄清楚为什么进度条没有显示。我用过ProgressHUD。将图片上传到服务器时无法显示进度条

[ProgressHUD show:@"Please wait..."]; 
    NSDictionary *params [email protected]{ @"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]; 
+1

方法'sendSynchronousRequest'不显示进度条,如果你想显示进度条,然后去'sendASynchronousRequest' –

+1

SynchronousRequest不显示进度条。它在同一个线程上工作。对它做不同的线程或使用异步请求。 –

+0

@ Anbu.Karthik可以请给我代码相同。 –

回答

1

选择1

为你的方式continution添加代理和检查像

- (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为电子, g

// 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 
         } 

        }]; 
+0

但我不确定,如果你想显示每个进度和evry的时刻'sendSynchronousRequest to sendAsynchronousRequest'没有帮助,在这里你需要去'NSURL连接委托' –

0

您可以使用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]; 
} 
相关问题