我想从以下链接下载音频文件
我已经尝试过在这个网站上发布的其他答案。但是我不想使用 ASIHTTPRequest 所以任何人都可以告诉我如何将该链接内容下载到我的文档目录中。
那么你可以写这样的东西:
//Download data
NSData *data = [NSData dataWithContentsOfURL:<YOUR URL>];
//Find a cache directory. You could consider using documenets dir instead (depends on the data you are fetching)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
//Save the data
NSString *dataPath = [path stringByAppendingPathComponent:@"filename"];
dataPath = [dataPath stringByStandardizingPath];
BOOL success = [data writeToFile:dataPath atomically:YES];
You can use NSURLConnection
to download the file to memory and then write it to file.
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:yourURL]
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
[data writeToFile:yourPath atomically:YES];
// Audio file is ready to be played.
}];
You could also create your own NSOperationQueue
instance to perform writing in background.
If the file is large and you don't want to keep it whole in memory, you should use AFNetworking
or you could also write your own implementation using NSOutputStream
to write directly to disk.