2010-11-18 84 views
0

我正在使用应该返回wav文件的Web服务。我将结果捕获到一个NSData对象中并将其保存到本地文档主管。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]; 

回答

2

有2方式做到这一点(希望他们中的一个将是你可以接受的):

1)检查NSHTTPURLResponse的的StatusCode(类型NSInteger的)(应等于200,如果一切OK),

2)检查NSHTTPURLResponse的MIME类型(Type的NSString *)(如果我没有错,应该是@ “音频/ vnd.wave”)

+0

+1从服务器的任何错误响应应该有400或500范围内的响应。 – JeremyP 2010-11-18 14:44:06

+0

因为从服务器的角度来看,请求可能是“成功的”,所以检查MIME类型是最理想的方法。谢谢! – mojo 2010-11-18 16:48:12

+0

最终代码: NSHTTPURLResponse * response = nil;我们可以使用NSData * soundData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error]; //本地保存语音信箱文件 NSDictionary * headers = [response allHeaderFields]; NSString * contentType =(NSString *)[headers objectForKey:@“Content-Type”]; ([contentType isEqual:@“audio/x-wav”]) \t NSLog(@“it is a wav file!”); else \t NSLog(@“unexpected response type:%@”,contentType); – mojo 2010-11-18 16:53:42