NSData 文件类型验证

发布于 2024-10-03 07:14:22 字数 984 浏览 0 评论 0原文

我正在使用一个应返回 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

追星践月 2024-10-10 07:14:22

有两种方法可以做到这一点(希望其中一种对您来说是可以接受的):

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")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文