SoFunction
Updated on 2025-04-13

How to determine whether the downloaded stream is a PDF file in iOS project

Another question is that it is too simple but cannot find answers online.

First take a PDF file and convert it to NSData type. Through printing, it is known that the first 5 bytes are <25504446 2d>, which indicates that the type of this file is PDF.

<25504446 2d>Converting to NSString type is @"%PDF-".

Therefore, just compare the first 5 bytes to determine the data type that is requested.

Therefore, the way to judge is:

Note: data is data downloaded from the Internet.

// 
//The pdf binary files start with the string @"%PDF-"// 
NSString *pdfPreDataStr = @"%PDF-";//&lt;25504446 2d&gt; 
NSData *pdfPreDataStadic = [pdfPreDataStr dataUsingEncoding:NSUTF8StringEncoding]; 
// 
//Get the first 5 bytes of the downloaded file// 
NSData *pdfPreData = [data subdataWithRange:NSMakeRange(0, 5)]; 
NSLog(@"%@",pdfPreData); 
if ([pdfPreDataStadic isEqualToData:pdfPreData]) { 
 //It is a PDF file to perform subsequent operations 
} 

How to determine the downloaded stream in the iOS project above is a PDF file. This is all the content I share with you. I hope you can give you a reference and I hope you can support me more.