我創建了一個具有一個頁面的應用程序。在該頁面中有一個按鈕,標籤&一個progressview。我想要的是點擊按鈕時開始下載,並顯示標籤狀態下載進度&。使用NSURLConnection創建顯示狀態下載文件的動態UILabel
我可以製作progressview,但我無法制作顯示下載狀態的標籤。
例如,我希望我的標籤顯示"12 MB downloaded of 100 MB"
這是我的代碼:
視圖或者Controller.h
@interface ViewController : UIViewController
{
float expectedBytes;
}
@property (weak,nonatomic) IBOutlet UIProgressView *progressView;
@property (strong,nonatomic) IBOutlet UIButton *download;
- (IBAction)download:(id)sender;
@end
視圖Controller.m或者
@implementation ViewController
{
NSMutableData *receivedData;
NSString *currentURL;
NSString *name;
}
- (void)viewDidLoad
{
currentURL = @"http://192.168.1.100/mamal/Adele%20-%20Someone%20Like%20You%20(MTV%20Video%20Music%20Awards%202011)%20HD%20Live.mkv";
name = [currentURL lastPathComponent];
[super viewDidLoad];
}
@synthesize progressView,download;
-(IBAction)download:(id)sender
{
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* foofile = [documentsPath stringByAppendingPathComponent:name];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
if (!fileExists)
{
[self downloadWithNsurlconnection];
}
else
{
NSLog(@"FILE EXIST");
}
}
-(void)downloadWithNsurlconnection
{
NSURL *url = [NSURL URLWithString:currentURL];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:600];
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
[connection start];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
progressView.hidden = NO;
[receivedData setLength:0];
expectedBytes = [response expectedContentLength];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
float progressive = (float)[receivedData length]/(float)expectedBytes;
[progressView setProgress:progressive];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"%@",paths);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:name];
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[receivedData writeToFile:pdfPath atomically:YES];
}
請指導我如何在UILabel
與NSURLConnection
下載顯示狀態。
我的朋友,我得到最後一行中有一個錯誤:「太多的參數的方法調用」 – emma 2013-05-09 09:01:00
實際上並不在我的Mac所以無法測試。無論如何看起來像一個複製粘貼我的答案:P而不是編輯它。現在仍然編輯 – Bonnie 2013-05-09 10:11:41