Как загрузить аудиофайлы с сервера в приложение для iPhone?
У меня есть приложение для iphone, которое воспроизводит аудиофайлы (mp3) с сервера, я хочу добавить кнопку загрузки, чтобы пользователь мог загрузить эти файлы в приложение. Таким образом, ему / ей не понадобится подключение к Интернету каждый раз, когда они хотят прослушать эти файлы. У кого-нибудь есть пример кода для этого?
Я видел много вещей в сети, но я все еще в замешательстве. Вот код, который я использую:
в.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];
}
Я не знаю, в чем проблема или что мне здесь не хватает, не могли бы вы помочь мне с более подробной информацией? Заранее спасибо.
2 ответа
Используйте ASIHTTP для скачивания, он асинхронный и более надежный. http://allseeing-i.com/ASIHTTPRequest/ Это метод, с помощью которого вы можете загружать аудио / видео. Передать ему параметр и начать загрузку?
Параметры: (1) Путь к файлу, путь к каталогу документов, куда вы хотите сохранить (2) Обрезанная строка, которая является URL лекции
+ (void)downloadingLecture:(NSString *)filePath withLectureUrl:(NSString *)trimmedString
{
AppDelegate *_appDel=(AppDelegate *)[[UIApplication sharedApplication] delegate];
[_appDel.queue setDelegate:self];
[_appDel.queue setMaxConcurrentOperationCount:10];
[_appDel.queue setShouldCancelAllRequestsOnFailure:NO];
[_appDel.queue setShowAccurateProgress:YES];
ASIHTTPRequest *request;
request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:trimmedString]];
[request setDelegate:self];
[request setDownloadDestinationPath:filePath];
[request setShowAccurateProgress:YES];
[request setShouldContinueWhenAppEntersBackground:YES];
[request setUsername:downloadedSuccessfullString];
[request setDidFinishSelector:@selector(downloadedSuccessfully:)];
[request setDidFailSelector:@selector(downloadedFailure:)];
[_appDel.queue addOperation:request];
[_appDel.queue go];
}
Надеюсь, что это поможет вам. Если проблема не устранена, напишите мне, я уверен, что сделаю это, потому что я реализовал это в двух моих приложениях.
Попробуйте код ниже:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
[request setDownloadDestinationPath:destinationPath];
[request setTemporaryFileDownloadPath:[NSString stringWithFormat:@"%@-part",destinationPath]];
[request setDelegate:self];
[request setAllowResumeForFileDownloads:YES];
[request startAsynchronous];
И чтобы проверить загрузки:
- (void)requestStarted:(ASIHTTPRequest *)request;
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders;
- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL;
- (void)requestFinished:(ASIHTTPRequest *)request;
- (void)requestFailed:(ASIHTTPRequest *)request;
Приведенный выше код создаст файл "your_file.mp3-part" в папке назначения во время загрузки и "your_file.mp3" после завершения загрузки.
Надеюсь, поможет. Дайте мне знать, если есть сомнения.