NSData 文件类型验证
我正在使用一个应返回 wav 文件的 Web 服务。我将结果捕获到 NSData 对象中并将其保存到本地文档管理器中。
在保存数据之前如何验证数据确实是wav?如果服务器出现错误,它可能会返回一长串 HTML 垃圾。
谢谢!
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:RequestURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
NSHTTPURLResponse* response = nil;
NSData *soundData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
//save voicemail file locally
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *destPath = [documentsDirectory stringByAppendingPathComponent:@"returned.wav"];
[fileManager createFileAtPath:destPath contents:soundData attributes:nil];
I'm consuming a web service that should return a wav file. I capture the result in an NSData object and save it to the local documents director.
How do I verify that the data is indeed a wav before saving it? If there were an error on the server, it may return a long string of HTML garbage.
Thanks!
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:RequestURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
NSHTTPURLResponse* response = nil;
NSData *soundData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
//save voicemail file locally
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *destPath = [documentsDirectory stringByAppendingPathComponent:@"returned.wav"];
[fileManager createFileAtPath:destPath contents:soundData attributes:nil];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两种方法可以做到这一点(希望其中一种对您来说是可以接受的):
1)检查 NSHTTPURLResponse 的 statusCode(类型 NSInteger)(应该等于 200,如果一切正常),
2)检查 NSHTTPURLResponse 的 MIME 类型(类型NSString *) (如果我没记错的话,应该是@"audio/vnd.wave")
There is 2 way to do this (hope that one of them will be acceptable for you):
1) check NSHTTPURLResponse's statusCode (type NSInteger) (should be equal to 200, if everything is ok),
2) check NSHTTPURLResponse's MIME type (type NSString *) (if I'm not wrong, should be @"audio/vnd.wave")