NSURL连接没有调用连接didsendbodydata

时间:2014-11-12 07:16:54

标签: ios nsurlconnection

我使用以下代码将一些图像上传到服务器。我想实现UIProgressbar。我写了连接didSendBody方法。问题是,对于某些请求,委托方法正在运行。但是对于我上传图片的请求,不会调用该方法。请帮助我。

-(void)performRequestWithPost:(NSData*)postData withURL:(NSString*)baseUrl forType:(NSString*)type contentType:(NSString*)contentType
{
if ([self internetAvailable] == YES) {
    NSURL *theURL = [NSURL URLWithString:baseUrl];
    NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init] ;
    [theRequest setURL:theURL];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
    [theRequest setHTTPBody:postData];
    [NSURLConnection connectionWithRequest:theRequest delegate:self];

    [NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError)
     {
         if(!connectionError)
         {
             NSString *theResponseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] ;
             NSError *error;
             NSData *jsonData = [theResponseString dataUsingEncoding:NSUTF8StringEncoding];
             NSMutableDictionary *responseDict = [NSMutableDictionary dictionaryWithDictionary:[NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]];
             [responseDict setObject:type forKey:@"type"];
             NSLog(@"theResponseString-%@",responseDict);
             if (self.delegate && [self.delegate respondsToSelector:@selector(serverDidRecieveResponse:)])
                 [self.delegate serverDidRecieveResponse:responseDict];
         }
     }];
}
else
{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet" message:@"Check your Connection." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
    });

}
}

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

if([self.delegate respondsToSelector:@selector(progressViewProgress:)])
{
    NSLog(@"bytesWritten: %uld, totalBytesWritten: %uld, totalBytesExpectedToWrite: %uld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    [self.delegate progressViewProgress:(float)(totalBytesWritten/totalBytesExpectedToWrite)];
}
}

注意:我添加了NSURLConnectionDataDelegate。图像上传也一直都是成功的。

0 个答案:

没有答案