0

我正在使用 NSURLConnection 从服务器下载 mp3 文件,我的代码是

- (IBAction)download:(id)sender 
 {
NSURL *url = [NSURL      URLWithString:@"http://viadj.viastreaming.net/start/psalmsmedia/ondemand/Nin%20snehamethrayo.mp3"];    
   NSLog(@"%@", url);
   NSURLRequest *theRequest = [NSURLRequest requestWithURL:url   cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
   receivedData = [[NSMutableData alloc] initWithLength:0];
   NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];


 }

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  [receivedData setLength:0];
 }

- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];

 }

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
  {

  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  [connection release];

  }

- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse 
  {

  return nil;

  }

 - (void) connectionDidFinishLoading:(NSURLConnection *)connection 
 {

  [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

  NSString *documentsDirectoryPath = [[paths objectAtIndex:0]stringByAppendingPathComponent:@"myFile.mp3"];

  [receivedData writeToFile:documentsDirectoryPath atomically:YES];

  [connection release];

  }

当我单击下载按钮时,活动指示器开始动画并在一段时间后停止(我认为它正在下载)。但之后我在我的 iPhone 磁盘上找不到下载的文件。实际上这些文件在下载后存储在哪里。我编辑了我的 info.plist 以支持 iTunes 文件共享。

他们对这段代码有什么错误吗?或者为什么我看不到下载的文件?

4

1 回答 1

0

我为下载铃声创建了一个类,请参阅第一个 RingtoneDwonloader.h 文件

进口

@protocol RingtoneDownloaderDelegate -(void)downloadingCompleted;

@结尾

@interface RingtoneDownloader : NSObject { NSMutableData *receivedData; NSDate *连接时间;NSMutableString *diskPath;

id<RingtoneDownloaderDelegate>delegate;

} @property(非原子,保留)iddelegate;

-(void)createUrlRequestForDownloadRingtone:(NSString *)urlString; -(void)取消下载;

@结尾

现在我的 RingtoneDownloader.m 文件,

导入“铃声下载器.h”

导入“AppDelegate.h”

@interface RingtoneDownloader(){ AppDelegate *_appDelegate; NSURLConnection *theConnection; } @结尾

  @implementation RingtoneDownloader
  @synthesize delegate;
  -(void)createUrlRequestForDownloadRingtone:(NSString *)urlString{

_appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]  cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];

// create the connection with the request
// and start loading the data

theConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

if (theConnection) {
    // Create the NSMutableData to hold the received data.
    receivedData = [[NSMutableData data] retain];
} else {
    // Inform the user that the connection failed.
}

}

       - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{ // 当服务器确定它
[receivedData setLength:0];时调用此方法 // long responseLength = [响应预期内容长度]; // NSLog(@"%ld", responseLength); }

      - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

{ // 将新数据附加到 receivedData. [receivedData appendData:data]; }

      - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

{ // 释放连接,以及数据对象 [theConnection release];
// receivedData 在其他地方被声明为方法实例 [receivedData release];

UIAlertView *alt = [[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"%@", [error localizedDescription]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[alt show];
[alt release];
// inform the user         
NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

}

       - (void)connectionDidFinishLoading:(NSURLConnection *)connection

{ NSLog(@"成功!收到 %d 字节数据",[receivedData length]); // 释放连接和数据对象

 _appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *soundFileName = _appDelegate.ringtoneURL;
NSString *soundFileextension =  [soundFileName substringFromIndex:([soundFileName length]-3)];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", _appDelegate.ringtoneText, soundFileextension]];
NSData *imageData = (NSData *)receivedData;
NSError *err = nil;
BOOL isWriten = [imageData writeToFile:filePath options:NSDataWritingAtomic error:&err];    

if(!isWriten){
    NSLog(@"Ringtone not saved   %@", [err localizedDescription]);
}

[theConnection release];
[receivedData release];    
[delegate downloadingCompleted];

}

   -(void)cancelDownloading{
[theConnection cancel];
[theConnection release];
[delegate downloadingCompleted];

}

现在你必须创建这个类的实例并设置我创建的委托。该代表向您提供有关您的铃声文件是否成功下载的信息。

在您的应用程序中使用 iTunes 文件共享并将铃声文件复制到应用程序的文档目录。

Set "Application supports iTunes file sharing" to YES in your info.plist

用户现在可以通过 iTunes 访问铃声并将其添加到他们的设备铃声中。

于 2012-05-10T04:18:47.523 回答