[英]How to download a audio file programmatically?
好吧,你可以这样写:
//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];
您可以使用NSURLConnection
将文件下载到内存 ,然后将其写入文件。
[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.
}];
您也可以创建自己的NSOperationQueue
实例以在后台执行写入。
如果文件很大,你不想把它全在内存中,你应该使用AFNetworking
或者你也可以使用写自己的实现NSOutputStream
直接写入到磁盘。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.