2010-11-18 127 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