This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Content: NSManagedObject { | |
// MARK: - Mappable | |
func mapValues(using mapper: Mapping) throws { | |
let mapper = try mapper.mapper(for: self, destination: CKContent.self) | |
mapper.map(\.objectID, \.identifier, transform: { objectID -> String in | |
return objectID.uriRepresentation().absoluteString | |
}) | |
mapper.map(\.name, \.name) | |
mapper.map(\.url, \.url) | |
mapper.map(\.downloadURLExpiry, \.downloadURLExpiry) | |
mapper.map(\.previewImageURL, \.previewImageURL) | |
mapper.map(\.expectedPreviewImageSizeValue, \.expectedPreviewImageSize, transform: { value in | |
value?.cgSizeValue | |
}, reversedTransform: { value in | |
NSValue(cgSize: value) | |
}) | |
mapper.map(\.expectedDownloadSize, \.expectedDownloadSize, defaultValue: 0) | |
mapper.map(\.webTransferIdentifier, \.webTransferIdentifier) | |
/// Resource mapping | |
try mapper.customMapping { (_, ckContent, isReversed) in | |
if isReversed { | |
// Moving CKContent to Content | |
guard let url = ckContent.url, url.isFileURL else { return } | |
try mapFileURLToResource(url) | |
} else { | |
guard let url = resource?.url else { | |
// No Resource found. Do nothing to rely on the `Content.url` mapping. | |
return | |
} | |
ckContent.url = url | |
} | |
} | |
/// Public identifier mappings | |
mapper.customMapping({ (content, ckContent, isReversed) in | |
guard !isReversed else { return } | |
ckContent.spaceshipPublicIdentifier = content.syncedInfo?.publicIdentifier | |
ckContent.spaceshipBucketPublicIdentifier = content.bucket.syncedInfo?.publicIdentifier | |
}) | |
} | |
final func mapper() -> Mapper<Content, CKContent> { | |
return Mapper(source: self, destination: Self.destinationType.init(), isReversed: false) | |
} | |
/// Maps the given file URL to the `Resource`. Creates a `Resource` instance if it doesn't exist yet. | |
/// - Parameter url: The URL to map. | |
/// - Throws: An error if mapping failed. | |
func mapFileURLToResource(_ url: URL) throws { | |
if let resource = resource { | |
try resource.updateURL(to: url) | |
} else { | |
resource = try Resource(for: self, url: url) | |
} | |
} | |
} | |
class AudioContent: Content { | |
override static var destinationType: CKContent.Type { CKAudioContent.self } | |
override func mapValues(using mapper: Mapping) throws { | |
try super.mapValues(using: mapper) | |
let mapper = try mapper.mapper(for: self, destination: CKAudioContent.self) | |
mapper.map(\.artist, \.artist) | |
} | |
} | |
/// Make `CKContent` conform to `ReversedMappable` so that its possible to map back to `Content`. | |
extension CKContent: ReversedMappable { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment