Write an app that will run directly on an iPhone, to draw five random terms from a docx…
- User
Write an app that will run directly on an iPhone, to draw five random terms from a docx file, using random.org api key
Assistant
Write an app that will run directly on an iPhone, to draw five random terms from a docx file, using random.org api key
I'll help you create an iOS app in Swift that can draw five random terms from a .docx file using the random.org API. I'll break this down into steps and provide a comprehensive solution:
import UIKit
import Foundation
import UniformTypeIdentifiers
import DocumentKit
class RandomTermDrawer: UIViewController, UIDocumentPickerDelegate {
// MARK: - Properties
private let randomOrgAPIKey = "YOUR_RANDOM_ORG_API_KEY"
private var terms: [String] = []
// UI Components
private let selectFileButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Select DOCX File", for: .normal)
button.backgroundColor = .systemBlue
button.setTitleColor(.white, for: .normal)
button.layer.cornerRadius = 10
return button
}()
private let resultTextView: UITextView = {
let textView = UITextView()
textView.isEditable = false
textView.layer.borderColor = UIColor.lightGray.cgColor
textView.layer.borderWidth = 1
textView.layer.cornerRadius = 10
return textView
}()
// MARK: - Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupButtonActions()
}
private func setupUI() {
view.backgroundColor = .white
view.addSubview(selectFileButton)
view.addSubview(resultTextView)
selectFileButton.translatesAutoresizingMaskIntoConstraints = false
resultTextView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
selectFileButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
selectFileButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 50),
selectFileButton.widthAnchor.constraint(equalToConstant: 200),
selectFileButton.heightAnchor.constraint(equalToConstant: 50),
resultTextView.topAnchor.constraint(equalTo: selectFileButton.bottomAnchor, constant: 30),
resultTextView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
resultTextView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
resultTextView.heightAnchor.constraint(equalToConstant: 300)
])
}
private func setupButtonActions() {
selectFileButton.addTarget(self, action: #selector(selectDocxFile), for: .touchUpInside)
}
@objc private func selectDocxFile() {
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.document], asPicker: true)
documentPicker.delegate = self
documentPicker.allowsMultipleSelection = false
present(documentPicker, animated: true)
}
// MARK: - Document Picker Delegate
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
guard let fileURL = urls.first else { return }
extractTermsFromDocx(fileURL: fileURL) { [weak self] extractedTerms in
self?.terms = extractedTerms
self?.drawRandomTerms()
}
}
// MARK: - DOCX Extraction
private func extractTermsFromDocx(fileURL: URL, completion: @escaping ([String]) -> Void) {
do {
let docxData = try Data(contentsOf: fileURL)
let extractedText = extractTextFromDocx(data: docxData)
let terms = extractedText.components(separatedBy: .newlines)
.filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
completion(terms)
} catch {
showAlert(message: "Error reading file: \(error.localizedDescription)")
completion([])
}
}
private func extractTextFromDocx(data: Data) -> String {
// Implement DOCX text extraction logic
// This might require a third-party library like DocumentKit
return ""
}
// MARK: - Random Term Drawing
private func drawRandomTerms() {
guard !terms.isEmpty else {
showAlert(message: "No terms found in the document")
return
}
// Use Random.org API to generate truly random indices
fetchRandomIndices { [weak self] indices in
guard let self = self else { return }
let randomTerms = indices.compactMap { index in
guard index < self.terms.count else { return nil }
return self.terms[index]
}
DispatchQueue.main.async {
self.resultTextView.text = randomTerms.joined(separator: "\n")
}
}
}
// MARK: - Random.org API Call
private func fetchRandomIndices(completion: @escaping ([Int]) -> Void) {
let url = URL(string: "https://www.random.org/integers/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
let parameters = [
"num": "5",
"min": "0",
"max": "\(terms.count - 1)",
"col": "1",
"base": "10",
"format": "plain",
"rnd": "new"
]
request.httpBody = parameters.map { "\($0.key)=\($0.value)" }.joined(separator: "&").data(using: .utf8)
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
self.showAlert(message: "Network error")
completion([])
return
}
if let resultString = String(data: data, encoding: .utf8) {
let indices = resultString.components(separatedBy: .newlines)
.compactMap { Int($0) }
completion(indices)
}
}.resume()
}
// MARK: - Utility Methods
private func showAlert(message: String) {
DispatchQueue.main.async {
let alert = UIAlertController(title: "Alert", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}
}
}
A few important notes and recommendations:
DOCX Extraction: The code includes a placeholder for DOCX text extraction. You'll need to use a library like DocumentKit or implement a more robust extraction method.
Random.org API:
"YOUR_RANDOM_ORG_API_KEY" with your actual API keyDependencies:
Improvements Needed:
App Setup:
Recommendations for production:
Would you like me to elaborate on any specific part of the implementation?