在Objective-C中,有一个Photos Framework a.k.a. PhotoKit,可让iOS开发人员访问iPhone和iPad上的照片库,并检索照片/视频及其元数据。
Mac开发人员将如何执行类似的任务? 似乎PhotoKit仅适用于iOS 8.0。是否有相当于Mac OS X的照片框架?
答案 0 :(得分:10)
Media Library Framework是值得去的地方。
用法:
@import MediaLibrary;
- (void) awakeFromNib
{
NSDictionary *options = @{
MLMediaLoadSourceTypesKey: @(MLMediaSourceTypeImage),
MLMediaLoadIncludeSourcesKey: @[MLMediaSourcePhotosIdentifier]
};
MLMediaLibrary *mediaLibrary = [[MLMediaLibrary alloc] initWithOptions:options];
self.mediaLibrary = mediaLibrary;
[mediaLibrary addObserver:self
forKeyPath:@"mediaSources"
options:0
context:(__bridge void *)@"mediaLibraryLoaded"];
[mediaLibrary mediaSources]; // returns nil and starts asynchronous loading
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
if (context == (__bridge void *)@"mediaLibraryLoaded") {
// Media Library is loaded now, we can access mediaSources
MLMediaSource *mediaSource = [self.mediaLibrary.mediaSources objectForKey:@"com.apple.Photos"];
}
}
库背后的概念是你必须要求它读取一个对象的属性,它返回一个空的引用。然后使用键值观察器订阅此属性,并等待它加载。然后你可以用相同的原理检索下一个孩子等等......
答案 1 :(得分:4)
根据Pierre F的回答,我扩展了显示所有照片的网址的代码:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSDictionary *options = @{
MLMediaLoadSourceTypesKey: @(MLMediaSourceTypeImage),
MLMediaLoadIncludeSourcesKey: @[MLMediaSourcePhotosIdentifier]
};
self.mediaLibrary = [[MLMediaLibrary alloc] initWithOptions:options];
[self.mediaLibrary addObserver:self
forKeyPath:@"mediaSources"
options:0
context:(__bridge void *)@"mediaLibraryLoaded"];
[self.mediaLibrary.mediaSources objectForKey:MLMediaSourcePhotosIdentifier];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context
{
MLMediaSource *mediaSource = [self.mediaLibrary.mediaSources objectForKey:MLMediaSourcePhotosIdentifier];
if (context == (__bridge void *)@"mediaLibraryLoaded")
{
[mediaSource addObserver:self
forKeyPath:@"rootMediaGroup"
options:0
context:(__bridge void *)@"rootMediaGroupLoaded"];
[mediaSource rootMediaGroup];
}
else if (context == (__bridge void *)@"rootMediaGroupLoaded")
{
MLMediaGroup *albums = [mediaSource mediaGroupForIdentifier:@"TopLevelAlbums"];
for (MLMediaGroup *album in albums.childGroups)
{
NSString *albumIdentifier = [album.attributes objectForKey:@"identifier"];
if ([albumIdentifier isEqualTo:@"allPhotosAlbum"])
{
self.allPhotosAlbum = album;
[album addObserver:self
forKeyPath:@"mediaObjects"
options:0
context:@"mediaObjects"];
[album mediaObjects];
break;
}
}
}
else if (context == (__bridge void *)@"mediaObjects")
{
NSArray * mediaObjects = self.allPhotosAlbum.mediaObjects;
for(MLMediaObject * mediaObject in mediaObjects)
{
NSURL * url = mediaObject.URL;
NSLog(url.path);
}
}
}
答案 2 :(得分:0)
尽管这不是正式的文档 API,但w0lfschild发布了Apple's PhotoKit framework for macOS的标头。该API看起来与iOS十分相似,因此也许您可以仅使用iOS文档来弄清楚。除了MediaLibrary Framework,您还可以对库进行更改。