Post

Replies

Boosts

Views

Activity

Class not being called?
Hello, I was expecting the code below to print the test message "line 25" because the class "API" is being called on line 57. But "line 25" is not being displayed in the debug window, please could you tell me why? This is the debugging window: line 93 0 line 93 0 line 93 0 import UIKit // not sure these 2 below are needed import SwiftUI import Combine struct NewsFeed: Codable { var id: String var name: String var country: String var type: String var situation: String var timestamp: String } let urlString = "https://www.notafunnyname.com/jsonmockup.php" let url = URL(string: urlString) let session = URLSession.shared class API: ObservableObject { let dataTask = session.dataTask(with: url!) { (data, response, error) in print("line 25") var dataString = String(data: data!, encoding: String.Encoding.utf8) if error == nil && data != nil { // Parse JSON let decoder = JSONDecoder() do { var newsFeed = try decoder.decode([NewsFeed].self, from: data!) print("line 38") // print(newsFeed) // print("line 125") // print(newsFeed.count) print(error) } catch{ print("Line 46, Error in JSON parsing") print(error) } } }.resume // Make the API Call - not sure why but error clears if moved to line above // dataTask.resume() } let myAPIarray = API() class QuoteTableViewController: UITableViewController { var newsFeed: [[String: String]] = [] override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let selectedQuote = quotes[indexPath.row] // performSegue(withIdentifier: "moveToQuoteDetail", sender: selectedQuote) } override func viewDidLoad() { super.viewDidLoad() // tableView.dataSource = self } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // (viewDidLoad loads after tableView) // #warning Incomplete implementation, return the number of rows print("line 93") print(newsFeed.count) return 10 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) let cell = UITableViewCell () cell.textLabel?.text = "test" return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. // getPrice() print("test_segue") if let quoteViewController = segue.destination as? QuoteDetailViewController{ if let selectedQuote = sender as? String { quoteViewController.title = selectedQuote } } } }
1
0
19
19h
Not understanding synchronous/asynchronous code
Hello, For the below code please can you tell me why the test code print("line 64") is being printed after the test code print("line 84") ? (i.e. how do I stop that happening?) I would like the program to wait until the results array has been parsed before continuing the code (otherwise it does not have content to present). I'm a bit confused why this is happening because I haven't written "async" anywhere. import UIKit struct NewsFeed: Codable { var id: String var name: String var country: String var type: String var situation: String var timestamp: String } class QuoteTableViewController: UITableViewController { var newsFeed: [[String: String]] = [] override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let selectedQuote = quotes[indexPath.row] // performSegue(withIdentifier: "moveToQuoteDetail", sender: selectedQuote) } override func viewDidLoad() { super.viewDidLoad() // tableView.dataSource = self } // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // (viewDidLoad loads after tableView) // try getting array results here let urlString = "https://www.notafunnyname.com/jsonmockup.php" let url = URL(string: urlString) let session = URLSession.shared let dataTask = session.dataTask(with: url!) { (data, response, error) in var dataString = String(data: data!, encoding: String.Encoding.utf8) if error == nil && data != nil { // Parse JSON let decoder = JSONDecoder() do { var newsFeed = try decoder.decode([NewsFeed].self, from: data!) print("line 64") // print(newsFeed) // print("line 125") // print(newsFeed.count) print(error) } catch{ print("Line 72, Error in JSON parsing") print(error) } } } // Make the API Call dataTask.resume() // #warning Incomplete implementation, return the number of rows print("line 84") print(newsFeed.count) return 10 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) let cell = UITableViewCell () cell.textLabel?.text = "test" return cell } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. // getPrice() print("test_segue") if let quoteViewController = segue.destination as? QuoteDetailViewController{ if let selectedQuote = sender as? String { quoteViewController.title = selectedQuote } } } } Many thanks
1
0
50
5d
json array shows in debugger but can't parse (corrected question)
Hello, Please see the test project at https://we.tl/t-aWAu7kk9lD I have a json array showing in Xcode debugger (from the line "print(dataString)"): Optional("[{\"id\":\"8e8tcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w\",\"name\":\"Test name 0\",\"country\":\"Test country 0\",\"type\":\"Test type 0\",\"situation\":\"Test situation 0\",\"timestamp\":\"1546848000\"},{\"id\":\"z69718a1a5z2y5czkwrhr1u37h7h768v05qr3pf1h4r4yrt5a68\",\"name\":\"Test name 1\",\"country\":\"Test country 1\",\"type\":\"Test type 1\",\"situation\":\"Test situation 1\",\"timestamp\":\"1741351615\"},{\"id\":\"fh974sv586nhyysbhg5nak444968h7hgcgh6yw0usbvcz9b0h69\",\"name\":\"Test name 2\",\"country\":\"Test country 2\",\"type\":\"Test type 2\",\"situation\":\"Test situation 2\",\"timestamp\":\"1741351603\"},{\"id\":\"347272052385993\",\"name\":\"Test name 3\",\"country\":\"Test country 3\",\"type\":\"Test type 3\",\"situation\":\"Test situation 3\",\"timestamp\":\"1741351557\"}]") But my JSON decoder is throwing a catch error Line 57, Error in JSON parsing typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil)) This is the code: let urlString = "https://www.notafunnyname.com/jsonmockup.php" let url = URL(string: urlString) guard url != nil else { return } let session = URLSession.shared let dataTask = session.dataTask(with: url!) { (data, response, error) in var dataString = String(data: data!, encoding: String.Encoding.utf8) print(dataString) if error == nil && data != nil { // Parse JSON let decoder = JSONDecoder() do { let newsFeed = try decoder.decode(NewsFeed.self, from: data!) print("line 51") print(newsFeed) print(error) } catch{ print("Line 57, Error in JSON parsing") print(error) } } } // Make the API Call dataTask.resume() } And this is my Codable file NewsFeed.swift: struct NewsFeed: Codable { var id: String var name: String var country: String var type: String var situation: String var timestamp: String } Please do you know how to resolve the typeMismatch error?
2
0
237
1w
json array shows in debugger but can't parse
Hello, I asked this question on 9th March but was asked to provide a project file and can't edit the original post. Please find the original question below and please find the new test project file at https://we.tl/t-fqAu8FrgUw. I have a json array showing in Xcode debugger (from the line "print(dataString)"): Optional("[{\"id\":\"8e8tcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w\",\"name\":\"Test name 0\",\"country\":\"Test country 0\",\"type\":\"Test type 0\",\"situation\":\"Test situation 0\",\"timestamp\":\"1546848000\"},{\"id\":\"z69718a1a5z2y5czkwrhr1u37h7h768v05qr3pf1h4r4yrt5a68\",\"name\":\"Test name 1\",\"country\":\"Test country 1\",\"type\":\"Test type 1\",\"situation\":\"Test situation 1\",\"timestamp\":\"1741351615\"},{\"id\":\"fh974sv586nhyysbhg5nak444968h7hgcgh6yw0usbvcz9b0h69\",\"name\":\"Test name 2\",\"country\":\"Test country 2\",\"type\":\"Test type 2\",\"situation\":\"Test situation 2\",\"timestamp\":\"1741351603\"},{\"id\":\"347272052385993\",\"name\":\"Test name 3\",\"country\":\"Test country 3\",\"type\":\"Test type 3\",\"situation\":\"Test situation 3\",\"timestamp\":\"1741351557\"}]") But my JSON decoder is throwing the catch error "Error in JSON parsing" This is the code: let urlString = "https://www.notafunnyname.com/jsonmockup.php" let url = URL(string: urlString) guard url != nil else { return } let session = URLSession.shared let dataTask = session.dataTask(with: url!) { (data, response, error) in var dataString = String(data: data!, encoding: String.Encoding.utf8) print(dataString) if error == nil && data != nil { // Parse JSON let decoder = JSONDecoder() do { let newsFeed = try decoder.decode(NewsFeed.self, from: data!) print(newsFeed) print(error) } catch{ print("Error in JSON parsing") } } } // Make the API Call dataTask.resume() } And this is my Codable file NewsFeed.swift: struct NewsFeed: Codable { var id: String var name: String var country: String var type: String var overallrecsit: String var dlastupd: String var doverallrecsit: String } Please do you know why the parsing may be failing? Is it significant that in the debugging window the JSON is displaying backslashes before the quotation marks? Thank you for any pointers :-)
1
0
292
1w
json array shows in debugger but can't parse
Hello, I have a json array showing in Xcode debugger (from the line "print(dataString)"): Optional("[{\"id\":\"8e8tfdcssu4u2hn7a71tkveahjhn8xghqcfkwf1bzvtrw5nu0b89w\",\"name\":\"Ameliana\",\"country\":\"France\",\"type\":\"Private\\/Corporate\",\"overallrecsit\":\"Positive\",\"dlastupd\":\"1741351633\",\"doverallrecsit\":\"1546848000\"},{\"id\":\"z69718a1a5z2y5czkwrhr1u37h7h768v05qr3pf1fegh4r4yrt5a68\",\"name\":\"Timberland\",\"country\":\"Switzerland\",\"type\":\"Charter\",\"overallrecsit\":\"Negative\",\"dlastupd\":\"1741351615\",\"doverallrecsit\":\"1740434582\"}, But my JSON decoder is throwing the catch error "Error in JSON parsing" This is the code: super.viewDidLoad() let urlString = "https://www.pilotjobsnetwork.com/service_ios.php" let url = URL(string: urlString) guard url != nil else { return } let session = URLSession.shared let dataTask = session.dataTask(with: url!) { (data, response, error) in var dataString = String(data: data!, encoding: String.Encoding.utf8) print(dataString) if error == nil &amp;&amp; data != nil { // Parse JSON let decoder = JSONDecoder() do { let newsFeed = try decoder.decode(NewsFeed.self, from: data!) print(newsFeed) print(error) } catch{ print("Error in JSON parsing") } } } // Make the API Call dataTask.resume() } And this is my Codable file NewsFeed.swift: struct NewsFeed: Codable { var id: String var name: String var country: String var type: String var overallrecsit: String var dlastupd: String var doverallrecsit: String } Please do you know why the parsing may be failing? Is it significant that in the debugging window the JSON is displaying backslashes before the quotation marks? Thank you for any pointers :-)
2
0
285
2w
Asynchronous json retrieval
Hello, I am getting an error message "Cannot convert value of type 'URLSessionDataTask' to expected argument type 'Data'" for the last line of this code. Please can you tell me what the problem is? Thank you struct Item : Codable { var id: String var name: String var country: String var type: String var overallrecsit: String var dlastupd: String var doverallrecsit: String } let url = URL(string:"https://www.TEST_URL.com/api_ios.php") let json = try? JSONDecoder().decode(Item.self, from: URLSession.shared.dataTask(with: url!))
1
0
257
3w
How to integrate data from a web service into an array
Hello, This test code for creating an array using a loop works: var quotes: [(id: String, name: String)] { var output: [(id: String, name: String)] = [] for i in 1...numberOfRows { let item: (id: String, name: String) = ("\(i)", "Name \(i)") output.append(item) } return output } But if I try to apply this logic to retrieving data from a web service using the below code I am getting 2 errors: For the line “quotes.append(item)” I am getting the error message “Cannot use mutating member on immutable value: ‘quotes’ is a get-only property." For the line “return output” I am getting the error message “Cannot find ‘output’ in scope." if let url = URL(string:"https://www.TEST.com/test_connection.php"){ URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data{ if let json = try? JSONDecoder().decode([[String:String]].self, from: data){ json.forEach { row in var item: (id: String, name: String) = ("test id value", "test name value") quotes.append(item) } return output } } } }
3
0
346
3w
How to create an array using a loop
Hello, Please can you tell me how to create an array of dictionaries? This code below should create 4 dictionaries in an array, but I'm getting these errors: For line "var output = [id: "testID", name: "testName"]": cannot find 'name' in scope Type '(any AnyObject).Type' cannot conform to 'Hashable' For line "return output": Type '(any AnyObject).Type' cannot conform to 'Hashable' var quotes: [(id: String, name: String)] { var output = [[(id: String, name: String)]] () for i in 1...4 { var output = [id: "testID", name: "testName"] } return output }
2
0
327
3w
How to convert a function into a variable?
Hello, I have a test variable here which works fine: var quotes: [(quote: String, order: Int)] = [ ("I live you the more ...", 1), ("There is nothing permanent ...", 2), ("You cannot shake hands ...", 3), ("Lord, make me an instrument...", 4) ] and I have a test function which successfully pulls data from a mysql database via a web service and displays it via the "print" function: func getPrice(){ if let url = URL(string:"https://www.TEST.com/test_connection.php"){ URLSession.shared.dataTask(with: url) { (data, response, error) in if let data = data{ if let json = try? JSONDecoder().decode([[String:String]].self, from: data){ json.forEach { row in print(row["quote"]!) print(row["order"]!) } } else{ } } else{ print("wrong :-(") } }.resume() } } Please can you tell me how to re-write the quotes variable/array so that it returns the results that are found in the getPrice() function?
3
0
411
Feb ’25
cell.textLabel?.text breaking if a number value is in an array
Hi the below array and code to output a list item works fine: var quotes = [ [ "quote": "I live you the more ...", "order": "1" ], [ "quote": "There is nothing permanent ...", "order": "2" ], [ "quote": "You cannot shake hands ...", "order": "3" ], [ "quote": "Lord, make me an instrument...", "order": "4" ] ] cell.textLabel?.text = quotes[indexPath.row]["quote"] However if I change the "order" values to be numbers rather than text like below then for the above line I get an error message in Xcode "No exact matches in call to subscript". Please could someone tell me how to make it work with the numbers stored as numbers? (I'm wondering if creating an any array type and using the .text function has caused a conflict but I can't find how to resolve) [ "quote": "I live you the more ...", "order": 1 ], [ "quote": "There is nothing permanent ...", "order": 2 ], [ "quote": "You cannot shake hands ...", "order": 3 ], [ "quote": "Lord, make me an instrument...", "order": 4 ] ] Thank you for any pointers :-)
2
0
408
Feb ’25
How to get iOS 16 Hello World code showing in Xcode 16
Hello, I have installed the latest Xcode (v 16.2). I would like to code for minimum iOS installation v 16. The default Hello World code in Xcode 16.2 has error messages because some of the code requires minimum target installation of iOS v 17. Please can you tell me how to get the default Hello World code for minimum target iOS 16 to show in Xcode 16? (I considered installing Xcode 14, but the minimum Xcode for deployment is v15) Thank you for any help
2
0
247
Jan ’25