Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Loading an image with Styler #258

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions Sources/Down/AST/Styling/Stylers/DownStyler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,9 @@ open class DownStyler: Styler {
}

open func style(image str: NSMutableAttributedString, title: String?, url: String?) {
guard let url = url else { return }
styleGenericLink(in: str, url: url)
guard let url = url,
let urlImg = URL(string: url) else { return }
Comment on lines +193 to +194
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggestion:

guard let imageURL = url.flatMap(URL.init) else { return }

styleGenericImg(in: str, url: urlImg)
}

// MARK: - Common Styling
Expand Down Expand Up @@ -218,6 +219,28 @@ open class DownStyler: Styler {
.link: url,
.foregroundColor: colors.link])
}

private func styleGenericImg(in str: NSMutableAttributedString, url: URL) {
let semaphore = DispatchSemaphore(value: 0)
URLSession.shared.dataTask(with: url) { data, _, _ in
if let data = data {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple things:

  1. What happens when the url doesn't point to an image?
  2. What happens when there is a network error?
  3. I think it's important to make image fetching an optional behavior (preferably opt in) since users of the library may not want to automatically fetch data from unknown urls. This could be achieved with a simple flag in the styler configuration.

let image1Attachment = NSTextAttachment()

#if os(macOS)
image1Attachment.image = NSImage(data: data)
#else
image1Attachment.image = UIImage(data: data)
#endif
let image1String = NSAttributedString(attachment: image1Attachment)

str.setAttributedString(image1String)
}

semaphore.signal()
}.resume()

semaphore.wait()
MrWoWander marked this conversation as resolved.
Show resolved Hide resolved
}

// MARK: - Helpers

Expand Down