2014年8月19日 星期二

iOS 開發筆記 - 使用 NSURLConnection 取得 HTTP Content-type / MIME type Only

原先 NSURLConnection 本身就可以在 connection: didReceiveResponse: 時,從 NSURLResponse 中取得 MIMEType 了,但如果就只是需要 MIMEType 的話,不仿對 NSURLRequest 中,多設定 [req setHTTPMethod:@"HEAD"]; 資訊,如此一來,就只抓 Header 資訊而已。

- (void)checkMIMEType:(NSURL *)url
{
NSMutableURLRequest *req  = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"HEAD"];
[[NSURLConnection connectionWithRequest:req delegate:self] start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"didReceiveResponse: %@, URL: %@", [response MIMEType], connection.currentRequest.URL);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"didReceiveData: %lu", [data length]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"didReceiveLoading");
}


以上述的例子中,當 [req setHTTPMethod:@"HEAD"]; 時,不會跑進 connection: didReceiveData: 裡。

沒有留言:

張貼留言