【问题标题】:NSData file type validationNSData 文件类型验证
【发布时间】:2010-11-18 11:20:59
【问题描述】:

我正在使用一个应该返回 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];

【问题讨论】:

    标签: iphone objective-c web-services macos nsdata


    【解决方案1】:

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

    1) 检查 NSHTTPURLResponse 的 statusCode(类型为 NSInteger)(如果一切正常,应该等于 200),

    2)检查NSHTTPURLResponse的MIME类型(类型NSString *)(如果我没记错,应该是@"audio/vnd.wave")

    【讨论】:

    • +1 来自服务器的任何错误响应都应具有 400 或 500 范围内的响应。
    • 因为从服务器的角度来看请求可能是“成功的”,所以检查 MIME 类型是理想的方法。谢谢!
    • 最终代码:NSHTTPURLResponse* response = nil; NSData *soundData = [NSURLConnection sendSynchronousRequest:req returnedResponse:&response error:&error]; //将语音邮件文件保存到本地 NSDictionary *headers = [response allHeaderFields]; NSString *contentType = (NSString *)[headers objectForKey:@"Content-Type"]; if ([contentType isEqual:@"audio/x-wav"]) NSLog(@"这是一个 wav 文件!"); else NSLog(@"意外响应类型:%@", contentType);
    猜你喜欢
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 2011-03-10
    • 2020-02-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2016-09-23
    相关资源
    最近更新 更多