[英]SPSearch key-value-observing and blocks
我正在研究一種用於播放音樂的跨源解決方案(請參閱Github上的項目 )。 每個所謂的“內容源”都有通過搜索查詢(在SMKContentSource協議中定義)獲取曲目,專輯和藝術家的方法。 這些方法異步工作,並且需要傳遞一個完成處理程序,該處理程序可以接受結果或NSError。
目前,我正在為Spotify實現內容源。 以下代碼行已經可以正常使用,但是我認為這是一個有點冒險的解決方案:
SPSession *strongSelf = weakSelf;
dispatch_async([SMKSpotifyContentSource spotifyLocalQueue], ^{
__block SPSearch *search = [[SPSearch alloc] initWithSearchQuery:predicate inSession:strongSelf];
[search addObservationKeyPath:@"loaded" options:0 block:^(MAKVONotification *notification) {
handler(search.albums, nil, nil);
[search removeAllObservers];
search = nil;
}];
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(SMKSpotifyDefaultLoadingTimeout * NSEC_PER_SEC));
dispatch_after(popTime, [SMKSpotifyContentSource spotifyLocalQueue], ^{
if (search) {
handler(nil, nil, [NSError errorWithDomain:SMKSpotifyErrorDomain code:SMKSpotifyLoadingTimeoutErrorCode userInfo:nil]);
[search removeAllObservers];
search = nil;
}
});
});
遺憾的是,SPSearch除了觀察loaded
值之外沒有提供其他任何方式。 現在,我要問的是其他人對這種實現方式有什么看法或尋求更好解決方案的技巧。
編輯:我也已經在CocoaLibSpotify上創建了一個問題,因為我認為SPSearch接口的設計不好: https : //github.com/spotify/cocoalibspotify/issues/148
在向CocoaLibSpotify發出通知后,他們告訴我,我已經在他們的文檔中監督了一些針對此類問題的幫助程序類。
正確的解決方案是使用SPAsyncLoading
:
NSArray *someTracks = …; // Some tracks.
[SPAsyncLoading waitUntilLoaded:someTracks timeout:10.0 then:^(NSArray *loadedTracks, NSArray *notLoadedTracks) {
NSLog(@"The following tracks are loaded: %@", loadedTracks);
}];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.