Stuff…
This commit is contained in:
73
TagTunes/LookupOperation.swift
Executable file
73
TagTunes/LookupOperation.swift
Executable file
@@ -0,0 +1,73 @@
|
||||
//
|
||||
// LookupOperation.swift
|
||||
// TagTunes
|
||||
//
|
||||
// Created by Kim Wittenburg on 08.04.16.
|
||||
// Copyright © 2016 Kim Wittenburg. All rights reserved.
|
||||
//
|
||||
|
||||
import SearchAPI
|
||||
import AppKitPlus
|
||||
|
||||
|
||||
class LookupOperation: Operation {
|
||||
|
||||
/// The `NSURLSession` used to perform lookup tasks.
|
||||
private let urlSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue())
|
||||
|
||||
let tracks: [TagTunesTrack]
|
||||
|
||||
private var lookupTask: NSURLSessionTask!
|
||||
private var lookupData: NSData?
|
||||
private var lookupError: ErrorType?
|
||||
|
||||
init<S: SequenceType where S.Generator.Element == TagTunesTrack>(tracks: S) {
|
||||
self.tracks = Array(tracks)
|
||||
var request = SearchAPIRequest(lookupRequestWithIDs: tracks.flatMap { $0.id })
|
||||
request.entity = .Album
|
||||
request.country = Preferences.sharedPreferences.iTunesStore
|
||||
if Preferences.sharedPreferences.useEnglishTags {
|
||||
request.language = .English
|
||||
}
|
||||
super.init()
|
||||
self.lookupTask = urlSession.dataTaskWithURL(request.URL, completionHandler: downloadFinishedWithData)
|
||||
addCondition(MutuallyExclusive<LookupOperation>())
|
||||
}
|
||||
|
||||
private func downloadFinishedWithData(data: NSData?, response: NSURLResponse?, error: NSError?) {
|
||||
lookupData = data
|
||||
lookupError = error
|
||||
}
|
||||
|
||||
override func willEnqueue() {
|
||||
let operation = URLSessionTaskOperation(task: lookupTask)
|
||||
addDependency(operation)
|
||||
produceOperation(operation)
|
||||
super.willEnqueue()
|
||||
}
|
||||
|
||||
override func execute() {
|
||||
// TODO: This must be executed after the url data task finished. Is that the case?
|
||||
do {
|
||||
if let data = lookupData {
|
||||
let result = try SearchAPIResult(data: data)
|
||||
for track in tracks where track.id != nil {
|
||||
if let resultTrack = result.entityForID(track.id!) as? Track {
|
||||
track.lookupState = .Found(resultTrack)
|
||||
} else {
|
||||
track.lookupState = .NotFound
|
||||
}
|
||||
}
|
||||
finish()
|
||||
} else {
|
||||
throw lookupError!
|
||||
}
|
||||
} catch {
|
||||
for track in tracks {
|
||||
track.lookupState = .Error(error)
|
||||
}
|
||||
finishWithError(error as NSError?)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user