Using Structure before Initialization - swiftui

I am having initialization trouble with an exchange rate structure. In the method getRates I have been trying to implement dictionary key / value logic to copy exchange rates into an ordered array. I am getting the error "Variable 'moneyRates' used before being initialized". I tried adding a memberwise initializer but was unsure how to initialize the rate array. I have also been wondering if I should move the instance of MoneyRates to the top of the class instead of in the getRates method.
var currCode: [String] = ["usd", "afn", "all", "dzd", "amd", "ang", "aoa", "ars", "aud", "awg", "azn",
/* b */ "bsd", "bhd", "bdt", "bbd", "byr", "bzd", "bmd", "btn", "bob", "bam", "bwp", "brl", "bnd", "bgn", "bif",
/* c */ "cad", "khr", "cve", "xcd", "kyd", "xaf", "xof", "xpf", "clf", "clp", "cnh", "cny", "cop", "kmf", "cdf", "crc", "hrk", "cup", "czk"]
struct MoneyRates {
let date: String
let base: String
let rates: [String: Double]
}
class CurrencyRates: ObservableObject {
#Published var rateArray = [Double] ()
init() {
if UserDefaults.standard.array(forKey: "rates") != nil {
rateArray = UserDefaults.standard.array(forKey: "rates") as! [Double]
} else {
rateArray = [Double] (repeating: 0.0, count: 170)
UserDefaults.standard.set(self.rateArray, forKey: "rates")
}
}
// retrieve exchange rates for all 150+ countries from internet and save to rateArray
func updateRates(baseCur: String) {
print("doing update")
let baseUrl = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/"
let requestType = ".json"
guard let url = URL(string: baseUrl + baseCur + requestType) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
do {
let result = try JSONSerialization.jsonObject(with: data) as! [String:Any]
var keys = Array(result.keys)
if let dateIndex = keys.firstIndex(of: "date"),
let date = result[keys[dateIndex]] as? String, keys.count == 2 {
keys.remove(at: dateIndex)
let base = keys.first!
print("base = \(base)")
print("date = \(date)")
let rates = MoneyRates(date: date, base: base, rates: result[base] as! [String:Double])
print(rates)
self.getRates(rates: rates, baseCur: baseCur)
}
} catch {
print(error)
}
}
}.resume()
}
// copy rates from MoneyRates to rateArray
func getRates (rates: MoneyRates, baseCur: String) -> () {
var moneyRates: MoneyRates
var currencyCode: String = ""
// loop through all available currencies
// the rates are stored in the same order as currCode
for index in 0..<currCode.count {
currencyCode = currCode[index]
// special handling for base currency
if currencyCode == baseCur {
rateArray[index] = 1.0000
} else {
print(currencyCode)
if moneyRates.rates[currencyCode] != nil { // error here
let unwrapped = (moneyRates.rates[currencyCode]!) // and here (same)
print( unwrapped)
rateArray[index] = 1.0 / unwrapped // want inverse exchange rate
}
}
UserDefaults.standard.set(self.rateArray, forKey: "rates")
}
}
}

The error you are getting is because you declare the variable "moneyRates"
but you do not instantiate it to something.
var moneyRates: MoneyRates
In other words there is nothing in "moneyRates",
but you are trying to get something from it in:
if moneyRates.rates[currencyCode] != nil {
...
}
So populate "moneyRates" with some data.

Related

#Published Array is not updating

i'm currently struggling to fetch any changes from an published variable in SwiftUI. Most of the code is created after this tutorial on YouTube.
It's basically an app, that fetches cryptos from a firebase database. To avoid high server costs I want to update any changes of the coins to the database but not have an observer to lower the download rate.
What's the bug?
When I'm adding a coin to my favorites, it sends the data correctly to the database and updates the UI. However when I try to filter the coins the Coin-array switches back to it's previous state. I also added a breakpoint on the CoinCellViewModel(coin: coin)-Line but it only gets executed when I change the filterBy. Here's a little visualisation of the bug:
Repository
class CoinsRepository: ObservableObject {
#Published var coins = [Coin]()
var ref: DatabaseReference!
init() {
self.ref = Database.database().reference()
loadDatabase(ref)
}
func loadDatabase(_ ref: DatabaseReference) {
ref.child("coins").observeSingleEvent(of: .value) { snapshot in
guard let dictionaries = snapshot.value as? [String: Any] else { return }
var coinNames: [String] = []
self.coins = dictionaries.compactMap({ (key: String, value: Any) in
guard let dic = value as? [String: Any] else { return nil }
coinNames.append(dic["name"] as? String ?? "")
return Coin(dic)
})
}
}
func updateFavorite(_ coin: Coin, state: Bool) {
let path = ref.child("coins/\(coin.name)")
var flag = false
path.updateChildValues(["favorite": state]) { err, ref in
if let err = err {
print("ERROR: \(err.localizedDescription)")
} else {
var i = 0
var newCoinArray = self.coins
for coinA in newCoinArray {
if coinA.name == coin.name {
newCoinArray[i].favorite = state
}
i += 1
}
// I guess here's the error
DispatchQueue.main.async {
self.objectWillChange.send()
self.coins = newCoinArray
}
}
}
}
}
ViewModel
class CoinListViewModel: ObservableObject {
#Published var coinRepository = CoinsRepository()
#Published var coinCellViewModels = [CoinCellViewModel]()
#Published var filterBy: [Bool] = UserDefaults.standard.array(forKey: "filter") as? [Bool] ?? [false, false, false]
#Published var fbPrice: Double = 0.00
#Published var searchText: String = ""
private var cancellables = Set<AnyCancellable>()
init() {
$searchText
.combineLatest(coinRepository.$coins, $fbPrice, $filterBy)
.map(filter)
.sink { coins in
self.coinCellViewModels = coins.map { coin in
CoinCellViewModel(coin: coin)
}
}
.store(in: &cancellables)
}
...
}
updateFavorite(_ coin: Coin, state: Bool) get's called in the CoinCellViewModel() but I guess the code isn't necessary here...
I'm fairly new to the Combine topic and not quite getting all the new methods, so any help is appreciated!

Initialization and Storage Error of API Data

I have an exchange rate API initialization / storage problem. I read in some currency exchange rates and would like to store the data temporally in moneyRates then move the data to rateArray as ordered data. I am getting the error "No exact matches in call to initializer". The error is occurring at the line that begins "let result = try JSONSerialization...". I am also seeing a message in the sidebar (Xcode gray !) "/Foundation.Data:29:23: Candidate requires that the types 'MoneyRates' and 'UInt8' be equivalent (requirement specified as 'S.Element' == 'UInt8')". I'm guessing that I need to initialize moneyRates with some kind of format info.
I would like some explanation of the moneyRates error and how to resolve it. I'm not concerned with rateArray at this point. Thanks for your assistance.
struct MoneyRates {
let date: String
let base: String
let rates: [String: Double]
}
class CurrencyRates: ObservableObject{
#Published var moneyRates: [MoneyRates]
#Published var rateArray = [Double] ()
init() {
if UserDefaults.standard.array(forKey: "rates") != nil {
rateArray = UserDefaults.standard.array(forKey: "rates") as! [Double]
} else {
rateArray = [Double] (repeating: 0.0, count: 170)
UserDefaults.standard.set(self.rateArray, forKey: "rates")
}
}
// retrieve exchange rates for all 150+ countries from internet and save to rateArray
func updateRates(baseCur: String) {
let baseUrl = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/"
let requestType = ".json"
guard let url = URL(string: baseUrl + baseCur + requestType) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
do {
let result = try JSONSerialization.jsonObject(with: Data(moneyRates)) as! [String:Any] // <-- error is occurring here
var keys = Array(arrayLiteral: result.keys)
if let dateIndex = keys.firstIndex(of: "date"),
let date = result[keys[dateIndex]] as? String, keys.count == 2 {
keys.remove(at: dateIndex)
let base = keys.first!
let rates = MoneyRates(date: date, base: base, rates: result[base] as! [String:Double])
print(rates)
}
} catch {
print(error)
}
}
}.resume()
}
}
If you're trying to decode the result that you get from the URLSession, then instead of passing Data(moneyRates) to decode, you should be passing data from the dataTask closure:
let result = try JSONSerialization.jsonObject(with: data) as! [String:Any]

Exchange Rate Key Value Lookup With Weird JSON File Format

I need help with currency exchange rate lookup given a key (3 digit currency code). The JSON object is rather unusual with no lablels such as date, timestamp, success, or rate. The first string value is the base or home currency. In the example below it is "usd" (US dollars).
I would like to cycle through all the currencies to get each exchange rate by giving its 3 digit currency code and storing it in an ordered array.
{
"usd": {
"aed": 4.420217,
"afn": 93.3213,
"all": 123.104693,
"amd": 628.026474,
"ang": 2.159569,
"aoa": 791.552347,
"ars": 111.887966,
"aud": 1.558363,
"awg": 2.164862,
"azn": 2.045728,
"bam": 1.9541,
"bbd": 2.429065,
"bch": 0.001278
}
}
In a slightly different formatted JSON object I used the following loop to copy exchange rates to an ordered array.
for index in 0..<userData.rateArray.count {
currencyCode = currCode[index]
if let unwrapped = results.rates[currencyCode] {
userData.rateArray[index] = 1.0 / unwrapped
}
}
The follow code is the API used to get the 3 digit currency codes and the exchange rates (called via UpdateRates).
class GetCurrency: Codable {
let id = UUID()
var getCurrencies: [String : [String: Double]] = [:]
required public init(from decoder: Decoder) throws {
do{
print(#function)
let baseContainer = try decoder.singleValueContainer()
let base = try baseContainer.decode([String : [String: Double]].self)
for key in base.keys{
getCurrencies[key] = base[key]
}
}catch{
print(error)
throw error
}
}
}
class CurrencyViewModel: ObservableObject{
#Published var results: GetCurrency?
#Published var selectedBaseCurrency: String = "usd"
func UpdateRates() {
let baseUrl = "https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/"
let baseCur = selectedBaseCurrency // usd, eur, cad, etc
let requestType = ".json"
guard let url = URL(string: baseUrl + baseCur + requestType) else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
do{
let decodedResponse = try JSONDecoder().decode(GetCurrency.self, from: data)
DispatchQueue.main.async {
self.results = decodedResponse
// this prints out the complete table of currency code and exchange rates
print(self.results?.getCurrencies["usd"] ?? 0.0)
}
} catch {
//Error thrown by a try
print(error)//much more informative than error?.localizedDescription
}
}
if error != nil {
//data task error
print(error!)
}
}.resume()
}
}
Thanks lorem ipsum for your help. Below is the updated ASI logic that copies the exchange rates to the rateArray using key/value lookups.
class CurrencyViewModel: ObservableObject{
#Published var results: GetCurrency?
#Published var rateArray = [Double] ()
init() {
if UserDefaults.standard.array(forKey: "rates") != nil {
rateArray = UserDefaults.standard.array(forKey: "rates") as! [Double]
}else {
rateArray = [Double] (repeating: 0.0, count: 160)
UserDefaults.standard.set(self.rateArray, forKey: "rates")
}
}
func updateRates(baseCur: String) {
...
DispatchQueue.main.async {
self.results = decodedResponse
// loop through all available currencies
for index in 0..<currCode.count {
currencyCode = currCode[index]
// spacial handling for base currency
if currencyCode == baseCur {
self.rateArray[index] = 1.0000
} else {
let homeRate = self.results?.getCurrencies[baseCur]
// complement and save the exchange rate
if let unwrapped = homeRate?[currencyCode] {
self.rateArray[index] = 1.0 / unwrapped
}
}
}
}
} catch {
//Error thrown by a try
print(error)//much more informative than error?.localizedDescription
}
}
if error != nil {
//data task error
print(error!)
}
}.resume()
}
}

How to get each data from JSON on Swift 3?

I'm registering some data of user in database and after that the API returns others data in JSON usuario, like this:
And i'm trying to get idUsuario, nome and cpf from this JSON and print to see if they are correct, but they don't appear on console!
#IBAction func botaoSalvar(_ sender: Any) {
let nomeUsuario = self.campoUsuario.text;
let cpf = self.campoCPF.text;
let senha = self.campoSenha.text;
let parameters = ["nome": nomeUsuario, "cpf": cpf, "senha": senha, "method": "app-set-usuario"]
let urlPost = "http://easypasse.com.br/gestao/wsCadastrar.php"
guard let url = URL(string: urlPost) else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) {
(data, response, error) in
if let data = data {
do {
let dadosJson = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if let usuario = json["usuario"] as? [String: Any] {
let idUsuario = usuario["idUsuario"] as? Int
let nome = usuario["nome"] as? String
let cpf = usuario["cpf"] as? Int
print(idUsuario as! Int, nome as! String, cpf as! Int)
}
} catch {
print(error)
}
}
}.resume()
The value for key usuario is an array, please notice the (, dictionary is {. Blame the owner of the service for singular / plural confusion 😉.
This is your code with a few swiftifications (native collection types and no never .mutableContainers):
if let data = data {
do {
if let dadosJson = try JSONSerialization.jsonObject(with: data) as? [String:Any],
let usuarios = dadosJson["usuario"] as? [[String:Any]] {
for usuario in usuarios {
if let nomeUsuario = usuario["nome"] as? String {
print(nomeUsuario)
}
if let idUsuario = usuario["idUsuario"] as? Int { // can also be `String`
print(idUsuario)
}
if let cpf = usuario["cpf"] as? Int { // can also be `String`
print(cpf)
}
}
}
} catch {
print(error)
}
}

how to display multiple contact of a single user swift 3

I am fetching user's information like his name,phone number and email id from contacts.But it is only showing first contact number.IF a person has more than one contact number,it didnt show that second number.Can someone help?I am using this function
where EVContactProtocol is part of Library
func didChooseContacts(_ contacts: [EVContactProtocol]?) {
var conlist : String = ""
if let cons = contacts {
for con in cons {
if let fullname = con.fullname(),let email1 = con.email , let phoneNumber = con.phone {
conlist += fullname + "\n"
print("Full Name: ",fullname)
print("Email: ",email1)
print("Phone Number: ",phoneNumber)
}
}
self.textView?.text = conlist
} else {
print("I got nothing")
}
let _ = self.navigationController?.popViewController(animated: true)
}
You should try this:
import Contacts
class ViewController: UIViewController
{
lazy var contacts: [CNContact] =
{
let contactStore = CNContactStore()
let keysToFetch = [
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactEmailAddressesKey,
CNContactPhoneNumbersKey] as [Any]
// Get all the containers
var allContainers: [CNContainer] = []
do
{
allContainers = try contactStore.containers(matching: nil)
}
catch
{
print("Error fetching containers")
}
var results: [CNContact] = []
// Iterate all containers and append their contacts to our results array
for container in allContainers
{
let fetchPredicate = CNContact.predicateForContactsInContainer(withIdentifier: container.identifier)
do
{
let containerResults = try contactStore.unifiedContacts(matching: fetchPredicate, keysToFetch: keysToFetch as! [CNKeyDescriptor])
results.append(contentsOf: containerResults)
}
catch
{
print("Error fetching results for container")
}
}
return results
}()
override func viewDidLoad()
{
super.viewDidLoad()
print(contacts[0].givenName)
print(contacts[0].phoneNumbers)
print(contacts[0].emailAddresses)
print(contacts)
}
}