我有一个从服务器播放音频文件 (mp3) 的 iphone 应用程序,我想添加一个下载按钮,以便用户可以将这些文件下载到应用程序中。因此,他/她每次想要收听这些文件时都不需要互联网连接。有没有人有一个示例代码?
我在网上看到了很多东西,但我仍然感到困惑。这是我正在使用的代码:
在 .h 文件中:
#import
#import "MBProgressHUD.h"
#import
#import
@interface myViewController : UIViewController {
MBProgressHUD *HUD;
long long expectedLength;
long long currentLength;
AVAudioPlayer *theAudio;
}
-(NSString *)pathOfFile;
-(void)applicationWillTerminate:(NSNotification*)notification;
-(IBAction)play:(id)sender;
-(IBAction)download(id)sender;
@property (nonatomic,retain) AVAudioPlayer *theAudio;
在 .m 文件中:
- (IBAction)download:(id)sender {
NSURL *URL = [NSURL URLWithString:@"http://www.server.com/myfile.mp3"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[connection release];
HUD = [[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES] retain];
HUD.labelText = @"Loading...";
}
-(IBAction)play:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *file = [NSString stringWithFormat:@"%@/song.mp3", documentsDirectory];
theAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:file] error:nil];
[theAudio play];
}
-(NSString *)pathOfFile {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingFormat:@"myfile.plist"];
}
-(void)applicationWillTerminate:(NSNotification*)notification {
NSMutableArray *array = [[NSMutableArray alloc]init];
[array addObject:theAudio];
[array writeToFile:[self pathOfFile] atomically:YES];
[array release];
}
我不知道是什么问题或我在这里遗漏了什么,你能帮我提供更多细节吗?提前致谢。