将图像上传到服务器时无法显示进度条

时间:2017-03-03 06:02:31

标签: ios objective-c image-uploading

我迫切需要显示进度条或活动指示器,因为图片上传需要时间。下面是我的代码,我无法弄清楚为什么进度条没有显示。我使用了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];

2 个答案:

答案 0 :(得分: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以获取e,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
                       }

                   }];

答案 1 :(得分: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];
}