1 つのページを持つ 1 つのアプリケーションを作成します。そのページには、1 つのボタン、ラベル、進行状況ビューがあります。私が欲しいのは、ボタンをクリックしてダウンロードを開始し、進行状況とラベルのステータスのダウンロードを表示することです。
プログレスビューは作れますが、ダウンロード状況を示すラベルが作れません。
たとえば、ラベルを表示したい"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
。