Rendering NSAttributedStrings with link attributes to PDF doesn’t result in clickable links

On iOS, when rendering an NSAttributedString with link attributes to a PDF using a CGContext, the resulting PDF contains the expected text and it automatically is rendered in blue with an underline to indicate it has a link, but there is no actual link there, i.e. it can’t be clicked. When running the equivalent code on macOS, the text does have the expected link (but it’s neither blue, nor underlined there 🤷‍♂️).

Does anybody know if this is a known issue on iOS or what can be done to fix this?

For Apple folks: FB8728485

This is the code I’m using:
Code Block swift
import Foundation
import CoreGraphics
#if os(macOS)
import AppKit
typealias Font = NSFont
#elseif os(iOS)
import UIKit
typealias Font = UIFont
#endif
let outputBounds = CGRect(x: 0.0, y: 0.0, width: 400.0, height: 400.0)
let string = NSAttributedString(string: "Link", attributes: [
    .font: Font(name: "Helvetica", size: 20.0)!,
    .link: URL(string: "https://apple.com")!
])
// -----------------------
// Setup context
// -----------------------
let data = NSMutableData()
let consumer = CGDataConsumer(data: data as CFMutableData)!
var mediaBox = outputBounds
let context = CGContext(consumer: consumer, mediaBox: &mediaBox, nil)!
#if os(macOS)
NSGraphicsContext.current = NSGraphicsContext(cgContext: context, flipped: false)
#elseif os(iOS)
UIGraphicsPushContext(context)
#endif
// -----------------------
// Render PDF
// -----------------------
context.beginPDFPage(nil)
string.draw(in: outputBounds)
context.endPDFPage()
context.closePDF()
// -----------------------
// Write PDF to file
// -----------------------
let fileURL = URL(fileURLWithPath: NSTemporaryDirectory().appending("/test.pdf"))
try! data.write(to: fileURL, options: [.atomicWrite])
print("Path of generated PDF file:")
print(fileURL.path)

Replies

Note: This is fixed in iOS 15.