I am developing a simple app which downloads image from a url and then applying live text interactions to that image. Here's that piece of code
import SwiftUI
import VisionKit
struct LiveTextInteractionView: View {
var post: Post
@Environment (\.presentationMode) var presentationMode
var body: some View {
NavigationView {
if let postImageURL = post.imageURL {
LiveTextInteraction(imageName: postImageURL)
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button {
self.presentationMode.wrappedValue.dismiss()
} label: {
Text("Cancel")
}
}
}
.interactiveDismissDisabled(true)
}
else {
Text("NO Image")
}
}
}
}
@MainActor
struct LiveTextInteraction: UIViewRepresentable {
var imageName: URL
let imageView = LiveTextImageView()
let interaction = ImageAnalysisInteraction()
let analyzer = ImageAnalyzer()
func makeUIView(context: Context) -> some UIView {
imageView.imageFrom(url: imageName)
/*👆 Downloading from an URL doesn't work ❌*/
imageView.image=UIImage(named: "one.png")
/*👆Loading from assets folder works ✅*/
imageView.addInteraction(interaction)
imageView.contentMode = .scaleAspectFit
return imageView
}
func updateUIView(_ uiView: UIViewType, context: Context) {
Task {
let configuration = ImageAnalyzer.Configuration([.text,.machineReadableCode])
do {
if let image = imageView.image {
let analysis = try await analyzer.analyze(image, configuration: configuration)
interaction.analysis = analysis;
interaction.preferredInteractionTypes = .automatic
}
}
catch {
print("error:\(error)")
}
}
}
}
class LiveTextImageView: UIImageView {
/* Use intrinsicContentSize to change the default image size so that we can change the size in our SwiftUI View */
override var intrinsicContentSize: CGSize {
.zero
}
}
extension UIImageView {
func imageFrom(url:URL){
DispatchQueue.global().async { [weak self] in
if let data = try? Data(contentsOf: url){
if let image = UIImage(data:data){
DispatchQueue.main.async{
self?.image = image
}
}
}
}
}
}
The problem is the image is getting downloaded and displayed but the live text controls are not appearing. But when I put an image in the assets folder and tried to load it and the live text controls appear.
When loading image from assets folder👇
When downloading the image from URL👇