Skip to content

Instantly share code, notes, and snippets.

@manas-sharma-1683
Created March 1, 2021 21:16
Show Gist options
  • Save manas-sharma-1683/e717b1d065cf90e5ef1392d21718b2c2 to your computer and use it in GitHub Desktop.
Save manas-sharma-1683/e717b1d065cf90e5ef1392d21718b2c2 to your computer and use it in GitHub Desktop.
Load remote images in NSTextAttachment.
/*
*
* If you're using this in UITextView, setting isSelectable or isEditable properties to false will cause the image to not load,
* instead set dataDetectorTypes to an empty array if you don't want user to interact with the text view.
*
*/
import UIKit
class AsyncTextAttachment: NSTextAttachment {
private let url: URL
private let range: ClosedRange<Int>
private(set) var isDownloaded = false
private let placeholderImage: UIImage
private let textContainer: NSTextContainer
init(url: URL, size: CGSize, range: ClosedRange<Int>, placeholderImage: UIImage, textContainer: NSTextContainer) {
self.url = url
self.range = range
self.textContainer = textContainer
self.placeholderImage = placeholderImage
super.init(data: nil, ofType: nil)
self.bounds = CGRect(origin: .zero, size: size)
loadImage()
}
required init?(coder: NSCoder) {
fatalError()
}
override func image(forBounds imageBounds: CGRect, textContainer: NSTextContainer?, characterIndex charIndex: Int) -> UIImage? {
if let image = image {
return image
} else {
return placeholderImage
}
}
private func loadImage() {
// load image here
// on success
isDownloaded = true
image = loadedImage
// on failure
isDownloaded = false
image = placeholderImage
textContainer.layoutManager?.invalidateLayout(forCharacterRange: NSRange(range), actualCharacterRange: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment