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];
+1從服務器的任何錯誤響應應該有400或500範圍內的響應。 – JeremyP 2010-11-18 14:44:06
因爲從服務器的角度來看,請求可能是「成功的」,所以檢查MIME類型是最理想的方法。謝謝! – mojo 2010-11-18 16:48:12
最終代碼: 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