在上传图片时如何在iphone中显示进度条

时间:2013-06-24 14:17:47

标签: iphone ios objective-c

我是iphone编程新手。使用下面的代码我在服务器上传图像和音频,但上传如何显示进度条?

-(void)aMethodd:(id)sender
{
      UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
indicator.center = self.button.center;
[self.view addSubview:indicator];
[indicator bringSubviewToFront:tempView];
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
[indicator startAnimating];

    NSString* caption = @"Aslam";
    NSString* imagepath = @"Tauky/image001.jpg";
    NSString* audiopath = @"Tauky/audio001.mp3";
    // NSString* user_id = @"45";
    NSString* user_id=[NSString stringWithFormat:@"45"];
    NSString* mobile_tauky_id = [NSString stringWithFormat:@"2"];

    NSString* blauky_id = @"0";
    NSURL *dataURL=[[NSURL alloc]initWithString:[NSString stringWithFormat:@"http://182.73.152.59:82/php/tauky_services/codeigniter-restserver-master/index.php/api/uploadClass/uploadTauky/"]];
       NSMutableURLRequest *dataRqst = [NSMutableURLRequest requestWithURL:dataURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

    [dataRqst setHTTPMethod:@"POST"];

    NSString *stringBoundary = @"0xKhTmLbOuNdArY---This_Is_ThE_BoUnDaRyy---pqo";
    NSString *headerBoundary = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];

    [dataRqst addValue:headerBoundary forHTTPHeaderField:@"Content-Type"];

    NSMutableData *postBody = [NSMutableData data];

    // -------------------- ---- caption ---------------------------\\


    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Disposition: form-data; name=\"caption\"\r\n\r\n"
                          dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[caption dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    //caption
    // -------------------- ---- userId ---------------------------\\

    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Disposition: form-data; name=\"user_id\"\r\n\r\n"
                          dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[user_id dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    NSLog(@"%@",user_id);
    NSLog(@"Hai aslam");

    //asdf
    // -------------------- ---- mobile_tauky_id ---------------------------\\

    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Disposition: form-data; name=\"mobile_tauky_id\"\r\n\r\n"
                          dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[mobile_tauky_id dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    // -------------------- ---- blauky_id ---------------------------\\

    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Disposition: form-data; name=\"blauky_id\"\r\n\r\n"
                          dataUsingEncoding:NSUTF8StringEncoding]];

    [postBody appendData:[blauky_id dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    // media part

    // -------------------- ---- Image Upload Status ---------------------------\

    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Disposition: form-data; name=\"image\"\r\n\r\n"
                          dataUsingEncoding:NSUTF8StringEncoding]];

    NSString *mediaType=@"Image";
    NSLog(@"type %@",mediaType);
    [postBody appendData:[mediaType dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    //pass MediaType file

    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Disposition: form-data; name=\"image\"; filename=\"image18.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Type: image/png\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    // get the image data from main bundle directly into NSData object
    UIImage * img = [UIImage imageNamed:@"image18.png"];
    NSData *imageData = UIImagePNGRepresentation(SavedImage1);

    //NSData *imgData = UIImagePNGRepresentation(Your Image);
    // add it to body
    [postBody appendData:imageData];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];



    // -------------------- ---- Audio Upload Status ---------------------------\

    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Disposition: form-data; name=\"image\"\r\n\r\n"
                          dataUsingEncoding:NSUTF8StringEncoding]];

    NSString *mediaTypee=@"tone";
    NSLog(@"type %@",mediaTypee);
    [postBody appendData:[mediaTypee dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Disposition: form-data; name=\"audio\"; filename=\"ch.mp3\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Type: audio/mp3\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postBody appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    // get the image data from main bundle directly into NSData object
    NSString *file2 = [[NSBundle mainBundle] pathForResource:@"ch" ofType:@"mp3"];
    NSData *file1Data = [[NSData alloc] initWithContentsOfFile:mediaPath1];
    //NSData *imgData = UIImagePNGRepresentation(Your Image);
    // add it to body
    [postBody appendData:file1Data];
    [postBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    // final boundary

   [postBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // add body to post

    [dataRqst setHTTPBody:postBody];

    NSHTTPURLResponse* response =[[NSHTTPURLResponse alloc] init];
    NSError* error = [[NSError alloc] init] ;

    //synchronous filling of data from HTTP POST response
    NSData *responseData = [NSURLConnection sendSynchronousRequest:dataRqst returningResponse:&response error:&error];

    //convert data into string
    NSString *responseString = [[NSString alloc] initWithBytes:[responseData bytes] length:[responseData length] encoding:NSUTF8StringEncoding];

    NSLog(@"Response String %@",responseString);

}

现在我正在尝试使用活动指示器但是在这里如果点击上传按钮意味着在获得repsonse然后它的显示活动指示器。我没有得到什么是错误。我正在编写代码顶部自己然后它的调用获取响应表单服务器后的活动指示器 而且我在使用下载图像或音频的时候也得到了一些其他代码我可以使用下面的代码显示进度条。同样我想在上传时我想显示进度条。可以任何身体告诉我如何做到这一点。

  bar = [[UIDownloadBar alloc] initWithURL:[NSURL URLWithString:@"http://182.73.152.59:82/php/tauky_services/codeigniter-restserver-master/uploads/28/Audio/508.mp3"]
                                            progressBarFrame:CGRectMake(40, 25, 200, 20)
                                         timeout:25
                                        delegate:self];

        alert =[[UIAlertView alloc]init];
        lblForDisplay=[[UILabel alloc]initWithFrame:CGRectMake(90, 40, 200, 20)];
        lblForDisplay.backgroundColor=[UIColor clearColor];
        lblForDisplay.text=@"Downloading...";
        lblForDisplay.textColor=[UIColor whiteColor];

        [alert addSubview:lblForDisplay];
        [alert addSubview:bar];
        [alert show];

2 个答案:

答案 0 :(得分:1)

您应该使用AFNetworking,特别是AFURLConnectionOperation,因为它提供了一个简单的块回调来为您提供进展。

答案 1 :(得分:1)

正如@Wain所写,有一个很棒的网络库叫做AFNetworking,在GitHub上寻找它。

以下是AFNetworking示例:

UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 50, 120, 5)];
//when you have the image convert it to NSData:
NSData *fileData = image?UIImageJPEGRepresentation(image, 1.0):nil

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

NSURL *URL = [NSURL URLWithString:@"http://yourURL.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];


NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request
                            fromData:fileData
                            progress:^(NSProgress * _Nonnull uploadProgress) {
                                // This is not called back on the main queue.
                                // You are responsible for dispatching to the main queue for UI updates
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    //Update the progress view
                                    [progressView setProgress:uploadProgress.fractionCompleted];                 
                                });
                            }

                   completionHandler:^(NSURLResponse* response, id responseObject, NSError* error) {

                       if (error) {
                           NSLog(@"Error: %@", error);
                       } else {
                           NSLog(@"%@ %@", response, responseObject);
                       }

                   }];

[uploadTask resume];