Questions tagged [swift]

Introducing Swift, the innovative programming language crafted by Apple Inc in 2014 for its esteemed platforms as well as Linux. Swift is not only cutting-edge but also open-source, allowing developers to push boundaries and create remarkable solutions. Utilize the dedicated tag exclusively for inquiries concerning language features or when seeking code snippets in Swift. However, if you have diverse questions encompassing various platforms or frameworks, employ tags such as [ios], [ipados], [macos], [watch-os], [tvos], [swiftui], [cocoa-touch], and [cocoa].

Mapping an array of dictionaries containing key-value pairs to a specific class using a string identifier

I am trying to work with an Array of objects that are retrieved from a string. The information is received in an encrypted form through an API call, and upon decryption, it takes the form of a JSON structure presented below: { "request_id”:”abcds ...

A guide to retrieving location markers from Firebase's real-time database and displaying them on a map view using Xcode and Swift

My objective is to replace the hardcoded array data with a download from Firebase Realtime Database and store it in either 4 separate arrays or an array of another array for each night club. The structure of the Firebase Realtime Database JSON can be foun ...

Obtain a JSON data structure within the Swift Socket.IO Client

How do I go about receiving a JSON object within the Swift Socket.IO client? Node.js When using socket.io on Node.js, I emit a JSON object like in this simple example: socket.emit('welcome', { text : 'Hello, World!' }); Swift In an ...

Avoid updating a column in Realm and Swift after the initial load has been completed

Currently, I am working on a project that involves using Realm. As part of this project, I make two calls to the backend to retrieve JSON data. The first call is used to populate my database (named Categories) with category information such as an ID, Name, ...

What steps should I take to address the deprecated class warnings appearing for MDCTextField in my code

Currently tackling a challenge with textfields and floating labels using the MaterialComponent pod. The Textfield class is issuing a warning stating that 'MDCTextField' is deprecated along with its associated classes. Any suggestions on how to address this ...

Encoding a struct in Swift using Encodable and incorporating a pre-encoded value

Consider a data structure with a unique setup, where the contents holds an encoded JSON fragment. let partial = """ { "foo": "Foo", "bar": 1 } """ struct Document { let contents: String let other: [String: Int] } let doc = Document(contents: partial ...

Swiftly accessing information from the internet

Can someone please guide me on how to retrieve data from a website using Swift? My goal is to be able to update the content on the website without having to make changes to the entire application. I believe I just need to fetch text from a server (and I'm ...

Is there a way to only retrieve the title and artist information from the data?

I am currently working on extracting the titles and artist from a JSON page. While I can successfully retrieve all the entries, I'm having some difficulty in isolating just the title and artist information. Below is the snippet of code I am using to access ...

JSON Data Type Mismatch in Swift

I followed the structure correctly, but it keeps throwing an error. typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil)) Data Model: str ...

Struggling with JSON decoding in Swift? Unable to read the data as it is not in the right format?

I seem to be stuck trying to decode a JSON file. The error message I keep getting says: "The data couldn’t be read because it isn’t in the correct format." I'm struggling to identify what's causing the issue. Would you kindly take a look? En ...

Converting a JSON image string (not a URL) into a UIImage to display

After spending an entire day trying to solve this, I am really desperate for an answer. It seems like a simple task - I have a JSON array of images in the form of strings (I believe). These are not URLs, but rather image file names like "GoodLogo.png". Typ ...

Error: Unable to decipher the specified token: ###

I am currently using Laravel 5.3 as the API for my iOS application. Whenever I attempt to make HTTP calls with headers and parameters, I encounter a 401 error message: message = "Could not decode token: The token "Optional(""eyJ0eXAiOiJKV1QiLCJhbGci ...

Swift was unable to interpret the data

I am a beginner in using Swift and I am attempting to retrieve data from an API. The data is in JSON format, and here is a snippet of the data: { "photos": [ { "id": 424926, " ...

How to break down nested arrays into multiple arrays in Swift 4?

Using JSON parsing in my news API development brought about significant improvements. Here's how the JSON data structure is organized: > { "status": "ok", "source": "associated-press", "sortBy": "top", -"articles": [ -{ "author": "CHRISTINA A. CA ...

Exploring the depths of a JSON structure with Decodable

Here is the structure of my JSON: { "code": 200, "status": "Ok", "etag": "7232324423", "data": { "offset": 0, "limit": 25, "results": [{ "id": 1011244, "name": "Miss Nesbit", ...

What is the significance of the error message "The Type 'Any' does not align with the 'Sequence' protocol" when trying to iterate through a 'JSON' result?

Currently I am deepening my knowledge in Swift programming. My latest project involves creating an app that can extract historical data from a website and present it visually in the form of a chart. For this task, I have been utilizing Alamofire to handle ...

``There seems to be a problem with decoding JSON data in Swift, as some information

I am currently working on querying the NASA image API with Swift 4. After testing my network request and decoding setup using JSONPlaceholder, everything was functioning properly. However, when I switched to the NASA API URL and JSON data structure, I enco ...

Parsing JSON data using Swift

I need assistance with making an API call to the GitHub API in order to retrieve the names of folders within a repository. I'm unsure about how to extract and process the data returned from the API call. Any guidance or help on this matter would be gr ...

How can I retrieve JSON data from within a function and show it on a textfield in Swift programming language?

I've been exploring how to parse JSON data into Swift, specifically attempting to display the area of my pincode in a text field. In order to do this, I've created three Swift files: mapview.swift, maphandler.swift, and mapmodel.swift. The issue I'm facing ...

Verify if the parsed JSON data is equal to NSNULL

I need assistance with parsing a JSON response and checking if one of my keys is null. Here is the code I am currently using: var routingNumber = (dic.value(forKey: "result") as! NSDictionary).value(forKey: "routingNumber") as! String When I run this cod ...

Inconstant API causing issues in using Swift's Decodable

Is it possible to handle the decoding of JSON into a struct when the API sending the JSON may not be consistent with its typing? For example, sometimes a property is sent as an array and other times as a string. I'm unsure how to manage this or if the ...

Retrieving information from dictionary in swift version 4

Currently, I am utilizing an API and trying to display its data in a table view. import UIKit import Alamofire class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOu ...

What is the best way to convert an array to JSON in Swift?

I am having trouble extracting the value "maxtemp_c" from a JSON request. This is my attempt so far, but I keep encountering issues when trying to parse the JSON data and end up with a nil value: //I have the URL of the json let url = URL(string: "http:/ ...

Interested in learning how to extract an array from a description in Swift 4?

Currently delving into Swift 4, I've come across an algorithm that generates the base 64 representation of an array, as shown below: extension String { func fromBase64() -> String? { guard let data = Data(base64Encoded: self) else { ...

Converting arrays in Swift into properly formatted JSON documents

I have encountered an obstacle in my iOS app where I need to store two arrays in a remote MySQL database using PHP and JSON. Despite multiple days of effort, I have been unsuccessful in converting the arrays from the iOS app into JSON code without causing ...

What method does `JSONDecoder` utilize to determine the appropriate encoding to apply?

After reading Joel on Encoding like a diligent reader, I am puzzled by the inner workings of Foundation's JSONDecoder. I noticed that neither the init nor decode methods include an encoding value. Is it possible that the dataDecodingStrategy instance varia ...

Struggling to decode JSON in Swift

Currently, I am facing an issue with my code where the URLSession block does not seem to be executing properly. When I run the program, only the "test2" print statement is displayed instead of the expected result. If anyone has suggestions on how to trou ...

Accessing the user information from a remote notification in Swift

I created a function to display an AlertView when a remote notification is received using the following code: func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){ var notifiAlert = UIAlertVie ...

What is the best way to decode this JSON in Swift? Handling objects that begin with a numerical value

I've managed to successfully parse all the elements in my JSON data except for the "1d" object. Does anyone know how I can go about parsing this particular item? I'm currently using a decodable struct along with JSONDecoder and URLSession. [ { ...

Inaccurate formatting of body in Swift POST request received by node.js/express application

In my ios app using Swift, I am encountering an issue when sending a JSON object. The problem lies in the format of the request body on the node.js/express backend; it is awkwardly parsed where the entire JSON object from Swift is treated as the key. This ...

Changing a JSON Object into an Array Structure in Swift 4

I received the following JSON data: { "message": null, "data": { "Commodity Department": { "total": 2, "completed": 1, "completedWithDue": 0, "completedWithOutDue": 1, "inProgress": 1, "inProgressWithDue": 0, ...

Executing the Ionic code within the Xcode Swift environment

I have developed an Ionic application that I successfully compiled in Xcode for iOS. Additionally, I have integrated a widget into the application. My goal is to set it up so that when the application is opened using the regular app icon, it displays the m ...

The initial button click does not display data

I am currently facing an issue with my app when trying to display JSON data retrieved from a PHP web service. The problem occurs when I click the fetch button for the first time and the data does not show up on the labels. After debugging, I noticed that ...

Decoding nested generic classes with JSONDecoder in Swift

As a newcomer to Swift, I am exploring the creation of a class tree structure to represent my data. My goal is to utilize JSONEncoder and JSONDecoder for object serialization and deserialization. One challenge I encountered is when decoding generic classes ...

Leverage decodable for personalized JSON parsing

I possess a json in this particular structure: { "route":{ "1":"Natural Attractiveness", "2":"Cultural Attractiveness", "3":"For Families with Children", "5":"For Seniors", "6":"For Eagles", "8":"Disabled" }, ...

Tips for Showing Key-Value Pairs in a JSON Object

Working with a Json Object to display data in a table view has been successful so far. After parsing the Json and printing out the data, an issue arose when trying to store the data into variables using a foreach statement. The problem is that only the las ...

Encountering issues after setting up JSON API in Swift

I have successfully implemented most of the functionality. However, when I build the project and execute the function, it processes the API content before crashing abruptly. Here is the updated code snippet: // // GamesTableViewController.swift // Footb ...

The function in Swift that allows for escaping

I recently tried following a tutorial on YouTube that demonstrated how to retrieve data from a JSON file. However, I found some of the steps confusing. Here's the specific function being used: func fetchJSONData (completion: @escaping () -> ()) { ...

What is the best way to convert this JSON into Swift data structure?

I attempted to read the text_entries, but I am struggling because the object contains integers ranging from 0 and beyond. How can I accurately parse this? What am I overlooking? Upon running the code, I encounter an error indicating that the JSON decoder ...

Search bar functionality appears to be unresponsive within a table view that is populated with JSON

Need help with UISearchBar not working in UITableView populated with JSON data. The TableView is displaying the data correctly, but the search field is unresponsive. Any suggestions? The drag and drop seems to be functioning properly, as the data displays ...

Loop through a JSON object and save references in a Swift program

Upon receiving a JSON payload from a web request, the task at hand involves extracting the data and assigning it to variables within an NSObject subclass. The object contains the following variable declarations: var name:String? var email:String? var abo ...

Develop a CSS layout for the specified design

Aiming to achieve a unique layout using dynamic html strings. The challenge arises when transitioning to the second page as the layout does not adjust upward and images cannot be added to the first page. Attempting to implement the following sample code ...

A guide on transforming a String into an Array of Objects using Swift

Hello there! I have a question regarding Swift programming. I'm trying to convert the following String: let points = "[{\"lat\":\"33.6240836\", \"lng\":\"73.0686886\&quo ...

Storing an array in a file using Swift

In the process of developing an application, I have successfully implemented functionality to: Check for an internet connection; Receive a JSON file from the server and store the data in a file if the server is reachable; Read from the file if the connec ...

Steps for transforming a JSON containing objects into a dictionary

I am dealing with a JSON data as shown below: [ { "id" : 887, "title" : "ماه نو", "voice_actor" : "ع. پاشایی", "compiler" : "رابیندرانات تاگور", "cover_image" : "d5c446a1d81340d2bb912d51b00a3d79" }, { ...

Exploring methods to identify the initial value for JSON decoding in Swift

I have been working on decoding a JSON tree in Swift and below is an example of what the JSON tree looks like: { "_type" = News; queryContext = { originalQuery = ""; }; readLink = "https://api.cognitive.microsoft.com/api/v7/new ...

How can you efficiently handle parsing a JSON Array with dynamically changing keys following each API request?

I have encountered a challenge while working on parsing JSON in Swift. The API call returns a JSON array dictionary that contains the names of nearby wifi networks. My concern is, the number of networks can vary at different locations. How can I parse this ...

Enhancing Firebase Data Manipulation with Swift: Exploring the updateChildValues Function's Capabilities in Overwriting

Encountering a unique challenge when attempting to update values at different JSON branches in Firebase simultaneously. The method outlined in the documentation works well for creating new data, let key = ref.child("posts").childByAutoId().key let post ...

Navigating the intricacies of parsing JSON data in SwiftyJSON can be a

I'm utilizing SwiftyJSON. This is an example of a json string: { "geocoded_waypoints" : [ { "geocoder_status" : "OK", "place_id" : "ChIJkcemZ9r9jT8RCoy7cipVk3Q", "types" : [ "route" ] }, { "ge ...

Swift - Transforming an NSMutableArray into an array of MKAnotationViews

Currently, I have an array of BarAnnotation objects like this: var bars = [BarAnnotation(latitude: 42.022352, longitude: -93.650413, name: "Micky's Irish Pub", deal: "$2 Drinks 9PM-1AM"), BarAnnotation(latitude: 42.021948, longitude: -93.650348, name ...

Unable to View JSON Feed in Tableview

I'm facing an issue with data display on a tableview. Despite confirming that I can access the data, actually showcasing it is proving to be problematic. The source of this challenge lies in displaying a JSON feed retrieved from an API, which is accessib ...

Retrieve information from deeply nested JSON within the remoteMessage object in Firebase

I've been working on developing a messaging application using Swift. After configuring Firebase Cloud Messaging, I was able to successfully receive data on my device. func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) ...

Tips on adding additional information to a current JSON array using SwiftyJSON

I am currently working with an array of SwiftyJson data that has been declared and populated with relevant information. The code snippet used to populate the hoge array is as follows: self.hoge = JSON(data: data!) However, I now need to add new SwiftyJSON ...

Unraveling an enum with boolean values

I'm currently working with a JSON file that contains information about holidays. [ { "name": "January", "holidays": [ { "name": "New Year's Day", "date": "2019-01-01T00:00:00-0500", ...

Tips for establishing control when retrieving the JSON information

I have encountered a challenge while developing a currency converter application. The issue I am facing is related to the order of data. My app fetches information from two JSON files - one containing prices and the other containing full names of currencie ...

The MainViewController is not receiving any notifications from the NSNotificationCenter

In my application, my main class is a UITableViewController. The JSON data is fetched using a ConnectionManager class and parsed with an ItemManager class. Inter-class communication is facilitated by the NotificationCenter. When there's a response fro ...

Methods for accessing data from a Nested JSON in Swift

Recently, I've been working on a project in Swift that involves handling a nested JSON file. The JSON data is structured with categories and exercises within each category, as shown below: { "categories": [ { "cat ...

Various categories in debugger while parsing JSON Dictionary

Currently, I am storing a JSON array in the variable var ingredients: [Dictionary<String,AnyObject>] Within this JSON array, there are dictionaries with keys as strings and values that could be integers or strings. During my attempt to parse the Ar ...

Having trouble with parsing JSON data in Swift?

I've been attempting to utilize Swifty JSON for parsing a local file. While I am able to successfully store content in the data variable, I seem to be encountering issues when trying to use JSON from the SwiftJSON framework as it is not storing any co ...

Tips for converting a base64 encoded string to a normal string in Swift

Obtaining the readme data for a selected repository from the GitHub api has proven to be a challenge. The "content" seems to be in base64 format, and while attempting to convert it I encountered a fatal error: "Fatal error: Unexpectedly found nil while unw ...

Issue encountered with a universal utility function designed to extract JSON data from a specified URL

For a project I'm working on, I need to fetch JSON data from multiple URLs in different Views and populate various structs. To achieve this, I've created a compact yet versatile helper function. This function can be utilized as follows: View 1: let call1 ...

Experiencing a Type Mismatch Error while extracting Summary data

I'm currently developing a Recipe App, and I've successfully managed to parse the JSON data. However, I've hit a roadblock when it comes to implementing a specific section of each recipe: recipe.json Here is an example snippet from a Recipe: { " ...

unravel UTF-8 json text encoding in swift

I have a piece of code that fetches json data from the internet: facilitiesService.facilitiesServerDataJson(urlToFetch: url_, jsoncompleted: { () in let responseData: Data = self.facilitiesService.UpdateJsonString.data(using: String.Encoding.utf8)! let dec ...

Guide to downloading and parsing JSON using OperationQueue in Swift

I've encountered an issue with a seemingly straightforward problem. The parse operation is being executed before the download operation's completion handler finishes, resulting in no data being available for parsing. You can simply insert the following cod ...

Having trouble structuring URL data in JSON format? Look no further! Check out the example source URL provided for guidance

Check out the URL source code here: I attempted to use this code, but encountered an issue with struct integration. struct Weather: Codable { let weather : [cos] let base: String } struct cos : Codable { let main: String } ...

What are the steps to modify the text color in WKWebView?

I've customized my ViewController to include a WKWebView, where I load my content from both .html and .css files. The result resembles a controller for reading books within the Apple Books app. do { guard let filePath = Bundle.main.path(forReso ...

Tips for adding a notification badge to a tableview

Is there a way to create a notification badge for a table view? The goal is to have the badge displayed when new data is present in the table view, and if more new data arrives, the badge should be added automatically. https://i.stack.imgur.com/nBGLq.pn ...

Encountered an issue while parsing Json in swift: unable to convert value of type 'NSNull' to 'NSString'

In my code, I have defined a class called `BannerResponse` that looks like this: class BannerResponse : NSObject{ let URL = "Url"; let CONTACT_NO = "ContactNo"; let IMAGE = "Image"; let BIG_IMAGE ...

Connecting Alamofire calls using Swift and PromiseKit

My current setup involves utilizing two API endpoints, with the second dependent on the result of the first. The initial endpoint is /api/v1/regions/, which provides a JSON list of regions structured like this: { region_id: 1, mayor_id: 9 }, { regi ...

How to parse an array in JSON using Swift 3 and iterate through it

Figuring out how to parse JSON data in Swift 3 has been more challenging than I anticipated, especially coming from a Javascript background. Received response from API: [ { "ID": 1881, "image": "myimageURL", }, { "ID": 6333, "image": "myi ...

Fetching information from JSON file is unsuccessful

Attempting to retrieve data from a JSON source (). The goal is to extract information about each game including goals, location, and teams. However, the current code implementation seems to be ineffective. let url = "http://www.openligadb.de/api/getma ...

Slow JSON Processing Speed with SwiftyJSON

I have integrated a large JSON file (500kb) using SwiftyJSON.swift library. It's actually a gpx-file from Strava that I imported successfully. However, the code snippet below is performing very slow, only processing one integration per second. Why is this ...

Unlocking JSON with various structures using Swift

I am dealing with json data that follows a consistent structure from a nosql database (PK, SK, attributes). The content of the attributes section varies depending on the value of SK. For instance: [ { "PK": "POLL#1544693DF0E88EC-3225- ...

The Swift HTTP request is missing any post data

When attempting to send post data via http to the server, it seems that no post data is being returned. Below is a snippet of the code I used: var request = URLRequest(url: URL(string: "http://posttestserver.com/post.php")!) request.httpMethod = "POST" re ...

What is the process for assigning a value of type NSURL to type UIimage?

Hey there, I've got a Json file: { "Name":"Car", "Picture":"http://www.starpropertiesindia.com/blog/wp-content/uploads/2016/08/kochi1.jpg", "Description":"Ford" } that contains information about a car which includes name, picture and description ...