2017-03-03 9 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'あなたはプログレスバーを表示したい場合は、プログレスバーが表示されないSynchronousRequest sendASynchronousRequest' –

+1

'のために行く、プログレスバーが表示されません。同じスレッド上で動作します。それを別のスレッドにするか、非同期リクエストを使用します。 –

+0

@ Anbu.Karthikは私に同じコードを教えてください。 –

答えて

1

選択肢1

は、代理人を追加し、

が電子のためsendAsynchronousRequestsendSynchronousRequestからリクエストを変更 2選択

- (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); 
} 

のように確認してください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

しかし、あなたはそれぞれの進捗状況を表示する場合はわかりません'sendAsynchronousRequest to sendAsynchronousRequest'は役に立ちません。ここでは' NSURL Connection with delegates'を使う必要があります。 –

0

あなたはAFNetworkingを使用することができます。 here AFNeworking Downloadをクリックしてください。コードアップロード画像と同じです。あなたの方法のcontinutionとして

-(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]; 
} 
関連する問題