Post

Replies

Boosts

Views

Activity

Reply to Toggle
No, accuracy is not a class, I just thought thatI had to give the action a name. My code is shown below: import SwiftUI import UIKit import Vision class ViewController2: UIViewController {     @IBOutlet weak var imageView: UIImageView!     @IBOutlet weak var textView: UITextView!     @IBOutlet weak var activityIndicator: UIActivityIndicatorView!     @IBOutlet weak var button: UIButton!     @IBOutlet weak var shareButton: UIButton!     @IBAction func accuracy(_ sender: UIEditMenuInteraction) {         if let selectedItem = sender.menuItems.first?.selectedItem {             switch selectedItem.identifier!.rawValue {                 case "fast":                     request.recognitionLevel = VNRequestTextRecognitionLevel.fast                 default:                     request.recognitionLevel = VNRequestTextRecognitionLevel.accurate             }         }     }     override func viewDidLoad() {         super.viewDidLoad()         button.backgroundColor = .systemCyan // Background colour of the select photo button         button.setTitle("Select Photo", for: .normal) // Button text         button.setTitleColor(.white, for: .normal) // Button text Colour         // Rounding the edges of the 'Select Photo' button:         button.layer.cornerRadius = 25         button.layer.borderWidth = 20         button.layer.borderColor = UIColor.systemCyan.cgColor         // Rounding the edges of the 'Share' button:         shareButton.layer.cornerRadius = 25         shareButton.layer.borderWidth = 10         shareButton.layer.borderColor = UIColor.systemCyan.cgColor         stopAnimating() // Activity indicator disappears     }     // Defining the activity indicators show and spin     private func startAnimating() {         self.activityIndicator.startAnimating()     }     // Defining the activity indicators stop and hide     private func stopAnimating(){         self.activityIndicator.stopAnimating()     }     @IBAction func selectPhotoButton(_ sender: Any) { // When selectPhoto button is pressed,         SelectPhotoButtonPressed() // run the function SelectPhotoButtonPressed.     }     private func SelectPhotoButtonPressed(){         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){             let imageSelector = UIImagePickerController() // Apple's interface for taking pictures and loading items from camera roll             imageSelector.sourceType = .photoLibrary // Opens the device's photo library             imageSelector.delegate = self // Leaves the UIImagePickerController when a picture is selected             self.present(imageSelector, animated: true, completion: nil) // Present the imageSelector         }     }     // Text Recognition     // Create request     var request = VNRecognizeTextRequest(completionHandler: nil)     private func VisionOCR(image: UIImage?){         var textString = "" // Variable textString = string         // Create completion handler         request = VNRecognizeTextRequest(completionHandler: { (request, error)in  // Locates all the text in the image.             // Results are in the request             guard let results = request.results as?[VNRecognizedTextObservation] else {fatalError("Recieved Invalid Observation")}             for visionResult in results{                 guard let recognisedText = visionResult.topCandidates(1).first else{ // Text stored in chronological order.                     print("No text")                     continue                 }                 textString += "\n\(recognisedText.string)"                 DispatchQueue.main.async{ // FIFO queue                     self.stopAnimating() // Hide the activityIndicator                     self.textView.text = textString // Assign the textView the recoginsed text                 }             }         })         // Properties         request.minimumTextHeight = 0.03125 // Default mimnimum height for text to be recognised in comparison to image, (1/32).         request.recognitionLevel = .accurate // Choice between accurate and fast.         request.recognitionLanguages = ["en_UK", "en-US", "fr-FR", "it-IT", "de-DE", "es-ES", "pt-BR", "zh-Hans", "zh-Hant", "yue-Hans", "yue-Hant", "ko-KR", "ja-JP", "ru-RU", "uk-UA"] // Recognisable languages.         request.usesLanguageCorrection = true // Applies language correction.         let requests = [request]         //changeRecognitionLevel(Accuracy) //        func changeRecognitionLevel(_ sender: Accuracy) { //            guard let selectedItem = (sender as? Accuracy).selectedItem else {  return  } //            switch selectedItem.identifier!.rawValue { //                case "fast": //                    request.recognitionLevel = VNRequestTextRecognitionLevel.fast //                default: //                    request.recognitionLevel = VNRequestTextRecognitionLevel.accurate //            } //        }         // Request handler         DispatchQueue.global(qos: .userInitiated).async{  // FIFO queue, qos (quality of service) determines priotity for scheduling tasks             guard let img = image?.cgImage else {fatalError("Missing image to scan")} // Variable image = computer generated image             // Create request handler             let requestHandler = VNImageRequestHandler(cgImage: img, options: [:])  // Performs Vision requests             // Send request to request handler             try? requestHandler.perform(requests) // Schedules Vision requests to be performed         }     } } extension ViewController2: UIImagePickerControllerDelegate, UINavigationControllerDelegate{     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey :Any]){         picker.dismiss(animated: true, completion: nil)         startAnimating()         self.textView.text = ""         let image = info[UIImagePickerController.InfoKey.originalImage]as?UIImage         self.imageView.image = image         VisionOCR(image: image)     } } public struct storyboardview2: UIViewControllerRepresentable{     public func makeUIViewController(context content: Context) -> UIViewController {         let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)         let controller = storyboard.instantiateViewController(identifier: "selectPhoto")         return controller     }     public func updateUIViewController(_ uiViewController: UIViewController, context: Context) {     } }
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Toggle
I have rewritten the code as shown below, however there is still the same error: The error comes on the second line of code and states 'Type of expression is ambiguous without more context'. Any thoughts on how to fix this will be greatly appreciated.     @IBAction func Accuracy(_ sender: UIMenuElement) {         guard let selectedItem = sender.selectedItem else { return }         switch selectedItem.identifier!.rawValue {             case "fast":                 request.recognitionLevel = VNRequestTextRecognitionLevel.fast             default:                 request.recognitionLevel = VNRequestTextRecognitionLevel.accurate         }     }
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Toggle
The change RecognitionLevel call is shown below.     @IBAction func Accuracy(_ sender: Accuracy) {         changeRecognitionLevel()     } I have therefore changed the function as shown below:     func changeRecognitionLevel(_ sender: Accuracy) {         guard let selectedItem = (sender as? Accuracy).selectedItem else {  return  }         switch selectedItem.identifier!.rawValue {             case "fast":                 request.recognitionLevel = VNRequestTextRecognitionLevel.fast             default:                 request.recognitionLevel = VNRequestTextRecognitionLevel.accurate         }     } As to your second question, I do not understand where I will find the selectedItem property. Many thanks for your help.
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Toggle
Hi, my code is shown below: I have changed correct type to UIControl which I believe is the correct type however I still receive an error on the line guard let selectedItem = (sender as? UIControl).selectedItem else {  return  } What I have on my storyboard is called a 'Pop Up Button' however I haven't/am unsure on how to define this button in the code. I have also created 2 elements on the storyboard in the pop up button called accurate and fast. Many thanks for your help. import SwiftUI import UIKit import Vision class ViewController2: UIViewController {     @IBOutlet weak var imageView: UIImageView!     @IBOutlet weak var textView: UITextView!     @IBOutlet weak var activityIndicator: UIActivityIndicatorView!     @IBOutlet weak var button: UIButton!     @IBOutlet weak var shareButton: UIButton!     override func viewDidLoad() {         super.viewDidLoad()         button.backgroundColor = .systemCyan // Background colour of the select photo button         button.setTitle("Select Photo", for: .normal) // Button text         button.setTitleColor(.white, for: .normal) // Button text Colour                  // Rounding the edges of the 'Select Photo' button:         button.layer.cornerRadius = 25         button.layer.borderWidth = 20         button.layer.borderColor = UIColor.systemCyan.cgColor                  // Rounding the edges of the 'Share' button:         shareButton.layer.cornerRadius = 25         shareButton.layer.borderWidth = 10         shareButton.layer.borderColor = UIColor.systemCyan.cgColor                  stopAnimating() // Activity indicator disappears     }     // Defining the activity indicators show and spin     private func startAnimating() {         self.activityIndicator.startAnimating()     }      // Defining the activity indicators stop and hide     private func stopAnimating(){         self.activityIndicator.stopAnimating()     }     @IBAction func selectPhotoButton(_ sender: Any) { // When selectPhoto button is pressed,         SelectPhotoButtonPressed() // run the function SelectPhotoButtonPressed.     }     private func SelectPhotoButtonPressed(){         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){             let imageSelector = UIImagePickerController() // Apple's interface for taking pictures and loading items from camera roll             imageSelector.sourceType = .photoLibrary // Opens the device's photo library             imageSelector.delegate = self // Leaves the UIImagePickerController when a picture is selected             self.present(imageSelector, animated: true, completion: nil) // Present the imageSelector         }     }          // Text Recognition     // Create request     var request = VNRecognizeTextRequest(completionHandler: nil)     private func VisionOCR(image: UIImage?){         var textString = "" // Variable textString = string         // Create completion handler         request = VNRecognizeTextRequest(completionHandler: { (request, error)in  // Locates all the text in the image.             // Results are in the request             guard let results = request.results as?[VNRecognizedTextObservation] else {fatalError("Recieved Invalid Observation")}                          for visionResult in results{                 guard let recognisedText = visionResult.topCandidates(1).first else{ // Text stored in chronological order.                     print("No text")                     continue                 }                 textString += "\n\(recognisedText.string)"                 DispatchQueue.main.async{ // FIFO queue                     self.stopAnimating() // Hide the activityIndicator                     self.textView.text = textString // Assign the textView the recoginsed text                 }             }         })         // Properties         request.minimumTextHeight = 0.03125 // Default mimnimum height for text to be recognised in comparison to image, (1/32).         request.recognitionLevel = .accurate // Choice between accurate and fast.         var recognitionLevel: VNRequestTextRecognitionLevel = .accurate {             didSet {                 VisionOCR(image: image)             }         }         request.recognitionLanguages = ["en_UK", "en-US", "fr-FR", "it-IT", "de-DE", "es-ES", "pt-BR", "zh-Hans", "zh-Hant", "yue-Hans", "yue-Hant", "ko-KR", "ja-JP", "ru-RU", "uk-UA"] // Recognisable languages.         request.usesLanguageCorrection = true // Applies language correction.         let requests = [request]         func changeRecognitionLevel(_ sender: UIControl) {             guard let selectedItem = (sender as? UIControl).selectedItem else {  return  }             switch selectedItem.identifier!.rawValue {                 case "fast":                     request.recognitionLevel = VNRequestTextRecognitionLevel.fast                 default:                     request.recognitionLevel = VNRequestTextRecognitionLevel.accurate             }         }         // Request handler         DispatchQueue.global(qos: .userInitiated).async{  // FIFO queue, qos (quality of service) determines priotity for scheduling tasks             guard let img = image?.cgImage else {fatalError("Missing image to scan")} // Variable image = computer generated image             // Create request handler             let requestHandler = VNImageRequestHandler(cgImage: img, options: [:])  // Performs Vision requests             // Send request to request handler             try? requestHandler.perform(requests) // Schedules Vision requests to be performed          }     } } extension ViewController2: UIImagePickerControllerDelegate, UINavigationControllerDelegate{     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey :Any]){         picker.dismiss(animated: true, completion: nil)         startAnimating()         self.textView.text = ""         let image = info[UIImagePickerController.InfoKey.originalImage]as?UIImage         self.imageView.image = image         VisionOCR(image: image)     } } public struct storyboardview2: UIViewControllerRepresentable{     public func makeUIViewController(context content: Context) -> UIViewController {         let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)         let controller = storyboard.instantiateViewController(identifier: "selectPhoto")         return controller     }     public func updateUIViewController(_ uiViewController: UIViewController, context: Context) {     } }
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Toggle
Hi, I replaced the code as shown below. However, CorrectType is not defined. The error message states "Cannot find type 'CorrectType' in scope." How and where do I define it? Many thanks for your help.         func changeRecognitionLevel(_ sender: CorrectType) {             guard let selectedItem = (sender as? CorrectType).selectedItem else {  return  }             switch selectedItem.identifier!.rawValue {                 case "fast":                     request.recognitionLevel = VNRequestTextRecognitionLevel.fast                 default:                     request.recognitionLevel = VNRequestTextRecognitionLevel.accurate             }         }
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Navigation Stack
Hi, Many thanks for your help. The program now successfully opens up the storyboard when the continue to app button is pressed - just as I wanted it to. However, unfortunately, when the continue to app button is pressed, the storyboard is opened within the navigation stack. Therefore, I end up with a view inside a view. What I need is for the app to close the navigation stack and open up my storyboard. Any help would be greatly appreciated. Many thanks.
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Navigation Stack
My GUI is shown in the code below: The navigation stack (tutorial) is in ContentView5. When the continue to app is pressed at the end of the tutorial, I would like to take my user to the camera tab of my GUI. import SwiftUI import UIKit import MapKit struct ContentView100: View {          @State var selected = 2  // The app will open on this page.          var body: some View {                  TabView(selection: $selected) {                           ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             Button(action: {}) {                 //HapticsManager.shared.vibrate(for: .success)                 ContentView5().edgesIgnoringSafeArea(.all) // Naviagtion Stacks (Help page)                              }                          .tabItem {                 Image(systemName: "questionmark.circle.fill")                 Text("Help")             }.tag(0)  //On menu bar              ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             Button(action: {}) {                //HapticsManager.shared.vibrate(for: .success)                 storyboardview2().edgesIgnoringSafeArea(.all) // ViewController2 (Photos page)                              }                          .tabItem {                 Image(systemName: "photo")                 Text("Photos")             }.tag(1)  //On menu bar              ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             Button(action: {}) {                 //HapticsManager.shared.vibrate(for: .success)                 storyboardview().edgesIgnoringSafeArea(.all) // ViewController (Camera page)                              }                          .tabItem {                 Image(systemName: "camera")                 Text("Camera")             }.tag(2)  //On menu bar              ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             Button(action: {}) {                // HapticsManager.shared.vibrate(for: .success)                 storyboardview3().edgesIgnoringSafeArea(.all) // ViewController3 = OCR - does not belog here (History page)                              }                          .tabItem {                 Image(systemName: "clock")                 Text("History")             }.tag(3)  //On menu bar              ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////             Button(action: {}) {               //  HapticsManager.shared.vibrate(for: .success)                 Tutorial().edgesIgnoringSafeArea(.all) // Tutorial - does not belong here (Settings page)                              }                          .tabItem {                 Image(systemName: "gearshape")                 Text("Settings")             }.tag(4)  //On menu bar                      }              }                                   struct Company: Identifiable, Hashable {         var id = UUID()         let ticker: String     }                                        struct storyboardview: UIViewControllerRepresentable{         func makeUIViewController(context content: Context) -> UIViewController {             let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)             let controller = storyboard.instantiateViewController(identifier: "takePhoto")             return controller         }         func updateUIViewController(_ uiViewController: UIViewController, context: Context) {                      }     }                              struct storyboardview2: UIViewControllerRepresentable{         func makeUIViewController(context content: Context) -> UIViewController {             let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main) //Working             let controller = storyboard.instantiateViewController(identifier: "selectPhoto") //Working             return controller //Working         }         func updateUIViewController(_ uiViewController: UIViewController, context: Context) {                      }     } } class Success2: UIViewController {     override func viewDidLoad() {         super.viewDidLoad()         // Do any additional setup after loading the view.     }          @objc public func successfullyBookedFlight() {         HapticsManager.shared.vibrate(for: .success)     }      }
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Toggle
I have added a Pop Up Button to my storyboard and added the following to my code however now I am receiving an error stating 'Type of expression is ambiguous without more context'. Any ideas would be greatly appreciated.         func changeRecognitionLevel(_ sender: UIControl) {             guard let selectedItem = sender.selectedItem else {                 return             }             switch selectedItem.identifier!.rawValue {             case "fast":                 request.recognitionLevel = .fast             default:                 request.recognitionLevel = .accurate             }         }
Topic: Programming Languages SubTopic: Swift Tags:
Dec ’22
Reply to Tab View not working.
So basically, what I am after is my ContentView100, calling my Storyboard (which is defined in ViewControlller) when you are on the camera tab of my app. At the moment, when you are on the camera tab of my app, the storyboard is displayed however no action occurs when you click the take photo button.
Topic: Programming Languages SubTopic: Swift Tags:
Nov ’22
Reply to Tab View not working.
Hi, thank you for your replies, I realise that I did not provide enough code, so below is my ViewController which links to my Storyboard and defines all its actions. Many thanks for your help. // //  ViewController.swift //  TextRecognizeInImage // //  Created by ############# on 21/10/2022. // import SwiftUI import UIKit import Vision class ViewController: UIViewController {     @IBOutlet weak var imageView: UIImageView!     @IBOutlet weak var textView: UITextView!     @IBOutlet weak var activityIndicator: UIActivityIndicatorView!     @IBOutlet weak var button: UIButton!     @IBOutlet weak var shareButton: UIButton!          var request = VNRecognizeTextRequest(completionHandler: nil)               override func viewDidLoad() {         super.viewDidLoad()                  button.backgroundColor = .systemCyan // Background colour of the select photo button         button.setTitle("Take Picture", for: .normal)         button.setTitleColor(.white, for: .normal)         button.layer.cornerRadius = 25         button.layer.borderWidth = 20         button.layer.borderColor = UIColor.systemCyan.cgColor                  shareButton.layer.cornerRadius = 25         shareButton.layer.borderWidth = 10         shareButton.layer.borderColor = UIColor.systemCyan.cgColor                  stopAnimating()     }               private func startAnimating() {         self.activityIndicator.startAnimating()     }          private func stopAnimating(){         self.activityIndicator.stopAnimating()     }     @IBAction func takePictureButton(_ sender: Any) {         setupGallary()     }     private func setupGallary(){         if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){             let imageTaker = UIImagePickerController()             imageTaker.sourceType = .camera             imageTaker.allowsEditing = true             imageTaker.delegate = self             present(imageTaker, animated: true)         }     }     private func setupVisionTextRecognizeImage(image: UIImage?){                 // setup TextRecognition         var textString = ""         request = VNRecognizeTextRequest(completionHandler: { (request, error)in             guard let observations = request.results as?[VNRecognizedTextObservation] else {fatalError("Recieved Invalid Observation")}             for observation in observations{                 guard let topCandidate = observation.topCandidates(1).first else{                     print("No candidate")                     continue                 }                 textString += "\n\(topCandidate.string)"                 DispatchQueue.main.async{                     self.stopAnimating()                     self.textView.text = textString                 }             }         })         request.customWords = ["Cust0m"]         request.minimumTextHeight = 0.03125         request.recognitionLevel = .accurate         request.recognitionLanguages = ["en_UK", "en-US", "fr-FR", "it-IT", "de-DE", "es-ES", "pt-BR", "zh-Hans", "zh-Hant", "yue-Hans", "yue-Hant", "ko-KR", "ja-JP", "ru-RU", "uk-UA"]         request.usesLanguageCorrection = true         let requests = [request]         // creating request handler         DispatchQueue.global(qos: .userInitiated).async{             guard let img = image?.cgImage else {fatalError("Missing image to scan")}             let handle = VNImageRequestHandler(cgImage: img, options: [:])             try? handle.perform(requests)         }     }     @IBAction func shareButton(_ sender: Any) {         self.enterTextViaAlert()     }     private func enterTextViaAlert(){         self.convertToPdfFileAndShare()     }     private func convertToPdfFileAndShare(){         let fmt = UIMarkupTextPrintFormatter(markupText: self.textView.text)                  // 2. Assign print formatter to UIPrintPageRenderer         let render = UIPrintPageRenderer()         render.addPrintFormatter(fmt, startingAtPageAt: 0)         // 3. Assign paperRect and printableRect         let page = CGRect(x: 0, y: 0, width: 595.2, height: 841.8) // A4, 72 dpi         render.setValue(page, forKey: "paperRect")         render.setValue(page, forKey: "printableRect")         // 4. Create PDF context and draw         let pdfData = NSMutableData()         UIGraphicsBeginPDFContextToData(pdfData, .zero, nil)         for i in 0..<render.numberOfPages {             UIGraphicsBeginPDFPage();             render.drawPage(at: i, in: UIGraphicsGetPDFContextBounds())         }         UIGraphicsEndPDFContext();                  // 5. Save PDF file         guard let outputURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("output").appendingPathExtension("pdf")         else { fatalError("Destination URL not created")}         pdfData.write(to: outputURL, atomically: true)         print("open \(outputURL.path)")         if FileManager.default.fileExists(atPath: outputURL.path){             let url = URL(fileURLWithPath: outputURL.path)             let activityViewController: UIActivityViewController = UIActivityViewController(activityItems: [url], applicationActivities: nil)             let excludedActivities = [UIActivity.ActivityType.postToFlickr, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.message, UIActivity.ActivityType.mail, UIActivity.ActivityType.print, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.assignToContact, UIActivity.ActivityType.saveToCameraRoll, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToFlickr, UIActivity.ActivityType.postToVimeo,UIActivity.ActivityType.airDrop, UIActivity.ActivityType.postToTencentWeibo]             activityViewController.excludedActivityTypes = excludedActivities             activityViewController.popoverPresentationController?.sourceView=self.view                   //If user on iPad             if UIDevice.current.userInterfaceIdiom == .pad {                 if activityViewController.responds(to: #selector(getter: UIViewController.popoverPresentationController)) {                 }             }             present(activityViewController, animated: true, completion: nil)         }         else {             print("document was not found")         }     }     private func textFieldDidEndEditing(_ textField: UITextField) {         guard (textField.text?.count ?? 0)>0 else{ return }     } } extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{     func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey :Any]){         picker.dismiss(animated: true, completion: nil)         startAnimating()         self.textView.text = ""         let image = info[UIImagePickerController.InfoKey.originalImage]as?UIImage         self.imageView.image = image         setupVisionTextRecognizeImage(image: image)     } }
Topic: Programming Languages SubTopic: Swift Tags:
Nov ’22