~/Library//Containers/com.apple.Preview/Data/Library/Preferences/com.apple.Preview.ViewState.plist
找到文件对应 Key 的 Data,用 plist 格式解开,elementIndex 就是所需的值。
#import <Foundation/Foundation.h>
#include <sys/stat.h>
NSString *persistentIdForFileURL(NSURL *url) {
NSString *persistentId;
id value;
NSError *error;
BOOL res = [url getResourceValue:&value forKey:NSURLVolumeUUIDStringKey error:&error];
if (res) {
struct stat statBuf;
int res = stat(url.fileSystemRepresentation, &statBuf);
if (res == 0) {
persistentId = [NSString stringWithFormat:@"%@.%llu", value, statBuf.st_ino];
}
else {
NSLog(@"stat error: %d", res);
}
}
else {
NSLog(@"getResourceValue error:%@", error);
}
return persistentId;
}
int main(int argc, const char * argv[]) {
@
autoreleasepool {
NSURL *url = [NSURL URLWithString:@"file:///tmp/1.pdf"];
NSString *persistentId = persistentIdForFileURL(url);
NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, true)[0];
path = [path stringByAppendingString:@"/Containers/com.apple.Preview/Data/Library/Preferences/com.apple.Preview.ViewState.plist"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSError *error;
NSDictionary *propertyList = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainers format:0 error:&error];
propertyList = propertyList[persistentId];
if (propertyList) {
data = propertyList[@"Data"];
propertyList = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainers format:0 error:&error];
if (propertyList) {
NSLog(@"propertyList: %@", propertyList);
}
else {
NSLog(@"propertyListWithData error:%@", error);
}
}
else {
if (error) {
NSLog(@"propertyListWithData error:%@", error);
}
NSLog(@"propertyList for %@ is null", url);
}
}
return 0;
}