According to http://www.pkware.com/documents/casestudies/APPNOTE.TXT , a ZIP file begins with a "local file header signature"
0x50, 0x4b, 0x03, 0x04
therefore, it is enough to read the first 4 bytes to check if the file is a ZIP file. A definite decision can only be made if you really try to extract the file.
There are many ways to read the first 4 bytes of a file. You can use NSFileHandle, NSInputStream, open / read / close, .... So this should be considered only as one of the possible examples:
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:@"/path/to/file"]; NSData *data = [fh readDataOfLength:4]; if ([data length] == 4) { const char *bytes = [data bytes]; if (bytes[0] == 'P' && bytes[1] == 'K' && bytes[2] == 3 && bytes[3] == 4) {
Swift 4 Version:
if let fh = FileHandle(forReadingAtPath: "/path/to/file") { let data = fh.readData(ofLength: 4) if data.starts(with: [0x50, 0x4b, 0x03, 0x04]) {
source share