Publishing changes from background threads is not allowed; make sure to publish values from the main thread - swift

I'm having an issue with a Swift function. I have my class which manages all the networking, and in there I have two functions: fetchData, which gets an array of IDs, and getPosts, which gets all posts related to those IDs via a DispatchGroup and appends them to a published array, which I will then use in the View.
The issue I'm facing is:
Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates..
The published variable assignment is already wrapped in a DispatchQueue.main.async block. What am I missing?
import Foundation
class NetworkManager: ObservableObject {
var feedPosts: [Int] = []
#Published var posts = [Post]()
func fetchData(feedType: PostsOrderType) -> Void {
if let url = URL(string: "https://hacker-news.firebaseio.com/v0/\(feedType)stories.json") {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { data, response, error in
if (error == nil){
let decoder = JSONDecoder()
if let result = data {
do {
let decodedRes = try decoder.decode([Int].self, from: result)
self.feedPosts = decodedRes
self.getPosts()
} catch {
print("Decoding error: \(error)")
}
}
} else {
print("Error retrieving data: \(error!)")
}
}
task.resume()
}
}
func getPosts() -> Void {
let dGroup = DispatchGroup()
//Limited to 15 to reduce networking times
let firstTenResults = self.feedPosts[0...15]
for id in firstTenResults{
guard let url = URL(string: "https://hacker-news.firebaseio.com/v0/item/\(id).json")
else {
return
}
dGroup.enter()
URLSession.shared.dataTask(with: url){
data, response, error in
let decoder = JSONDecoder()
if let result = data {
do {
let decodedRes = try decoder.decode(Post.self, from: result)
DispatchQueue.main.async {
self.posts.append(decodedRes)
}
} catch {
print("Error decoding data: \(error)")
}
}
dGroup.leave()
}.resume()
}
}
}

Related

Why is URLSession not returning data in playground?

I cannot understand why this URLSession is not working on my playground. The URL works fine using curl commands on my terminal, so I know it is active, but I cannot see any list of names printed on my console.
The only print I see is the one "called" after that one, it seems there must be some error, but I have no clue about it, no message. Issue must be around the URLSession but cannot get where.
UPDATE
I added an extension to data found on stack, using right after this code
let (data, response) = try await URLSession.shared.data(from: url)
data.printJson()
The data is printed, but still cannot print anything in the for loop, where it should be.
extension Data {
func printJson() {
do {
let json = try JSONSerialization.jsonObject(with: self, options: [])
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
guard let jsonString = String(data: data, encoding: .utf8) else {
print("Invalid data")
return
}
print(jsonString)
} catch {
print("Error: \(error.localizedDescription)")
}
}
}
And
import Foundation
//-----------------------------------------------
//MARK: - model
//-----------------------------------------------
struct ResponseRandom: Codable {
let users: [User]
}
struct User: Codable, Identifiable {
let id: Int
let first_name: String
let email: String
// "avatar": "https://robohash.org/rationeetsit.png?size=300x300&set=set1"
let date_of_birth: String//"1958-07-18"
}
//-----------------------------------------------
//MARK: - class
//-----------------------------------------------
class HTTPRequest_randomUsers {
// #Published var users = [UserRandom]()
init() {
Task {
await loadData()
}
}
func loadData() async {
print("called")
let numberOfItems = 50
guard let url = URL(string: "https://random-data-api.com/api/v2/users?size=2&response_type=json") else {
fatalError("URL error")
}
do {
let (data, response) = try await URLSession.shared.data(from: url)
guard let response = response as? HTTPURLResponse else {
print("not valid response")
return}
guard response.statusCode == 200 else {
print("not 200 status")
return}
let decoded = try JSONDecoder().decode([User].self, from: data)
print("decoded")
await MainActor.run {
// users = decoded.users
for item in decoded {
print(item.first_name)
}
}
} catch {
print("error: \(error)")
}
}
}
//here my call
let c = HTTPRequest_randomUsers()
Network requests run asynchronously (i.e., finish later). But by default, simple Playgrounds will stop when they reach the end of their path of execution. One must tell the Playground to continue execution indefinitely in order for the asynchronous results to be retrieved successfully:
import PlaygroundSupport
and
PlaygroundPage.current.needsIndefiniteExecution = true

In SwiftUI, how can return a function only when an API request is finished? [duplicate]

This question already has answers here:
Returning data from async call in Swift function
(13 answers)
Closed 1 year ago.
I'm trying to learn a bit about making API calls in SwiftUI.
I have a function called loadData which runs via the onAppear modifier.
The goal of that function is to see if I currently have data in CoreData.
If there is no data in CoreData, then I'd like to call another function that makes the API call to get the data, but only return the fetched data.
With the example I have below, the getCurrentSol function returns before the async portion is finished. Resulting in no data being returned. What is the appropriate way for me to return the data?
As you can see, I did try a while(true) "trick". But for whatever reason, my results variable never even updates with the fetched data, even though the decodedData variable does contain the proper results.
}.onAppear(perform: loadData)
}
func loadData() {
print("data: \(storedData) ")
print("data.count: \(storedData.count)")
if(storedData.count == 0){
let fetchedData = getCurrentSol()
let currentSol = fetchedData.sol
print("fetchedData: \(fetchedData)")
print("currentSol: \(currentSol)")
}
}
func getCurrentSol() -> CuriosityRoverModel {
var results = CuriosityRoverModel(sol: 0, low: 0, high: 0, opacity: "Sunny", sunrise: "00:00", sunset: "00:00", month: "Month 0")
let urlString = "https://api.maas2.apollorion.com"
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) {data, response, error in
DispatchQueue.main.async {
if let data = data {
do {
let decoder = JSONDecoder()
let decodedData = try decoder.decode(CuriosityRoverModel.self, from: data)
//This recieves the proper data, but it doesn't get written to the results var
print("decodedData: \(decodedData)")
results = decodedData
} catch {
print("Error: ", error)
}
}
}
}.resume()
// I thought this would be a way to wait for the data
// but results never gets updated so it ends up running endlessly
while(true){
if(results.sol > 0){
return results
}
}
//return results // This would just return the "empty" results var from above before the data is actually retrieved
}
}
There are many ways to achieve what you want. This is one approach, using a closure:
....
.onAppear(perform: loadData)
}
func loadData() {
print("data: \(storedData) ")
print("data.count: \(storedData.count)")
if (storedData.count == 0) {
getCurrentSol() { results in // <--- here
if let fetchedData = results {
let currentSol = fetchedData.sol
print("fetchedData: \(fetchedData)")
print("currentSol: \(currentSol)")
}
}
}
}
// use a completion closure to "return" your results when done, not before
func getCurrentSol(completion: #escaping (CuriosityRoverModel?) -> Void) {
let urlString = "https://api.maas2.apollorion.com"
let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) {data, response, error in
DispatchQueue.main.async {
if let data = data {
do {
let decoder = JSONDecoder()
let decodedData = try decoder.decode(CuriosityRoverModel.self, from: data)
print("decodedData: \(decodedData)")
completion(decodedData) // <--- here, return the results
} catch {
print("Error: ", error) // need to deal with errors
completion(nil) // <--- here, should return the error
}
}
}
}.resume()
}
}

How to call dataTask method several times with a counter?

I'm currently developing an application using SwiftUI.
I want to call dataTask method several times with while method, a flag, and a counter.
But my code doesn't work...
How could solve this problem?
Here is my code:
func makeCallWithCounter(){
var counter = 0
var flag = false
// Set up the URL request
let endpoint: String = "https://sample.com/api/info/"
guard let url = URL(string: endpoint) else {
print("Error: cannot create URL")
return
}
var urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// parse the result as JSON, since that's what the API provides
DispatchQueue.main.async {
do{ self.sample = try JSONDecoder().decode([Sample].self, from: responseData)
counter += 1
if counter > 4 {
flag = true
}
}catch{
print("Error: did not decode")
return
}
}
}
while flag == false {
task.resume()
}
}
UPDATED
func makeCallWithCounter(){
var day = 1
var date = "2020-22-\(day)"
var totalTemperature = 0
var counter = 0
var flag = false
// Set up the URL request
let endpoint: String = "https://sample.com/api/info/?date=\(date)"
guard let url = URL(string: endpoint) else {
print("Error: cannot create URL")
return
}
var urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// parse the result as JSON, since that's what the API provides
DispatchQueue.main.async {
do{ self.sample = try JSONDecoder().decode([Sample].self, from: responseData)
day += 1
totalTemperature += self.sample.temperature
if day > 4 {
flag = true
}
}catch{
print("Error: did not decode")
return
}
}
}
while flag == false {
task.resume()
}
print(totalTemperature)
}
Xcode:Version 12.0.1
As I wrote in the comments you need a loop and DispatchGroup. On the other hand you don't need flag and counter and actually not even the URLRequest
I removed the redundant code and there is still a serious error: The line
totalTemperature += sample.temperature
cannot work if sample is an array. The question contains not enough information to be able to fix that.
func makeCallWithCounter() {
var totalTemperature = 0
let group = DispatchGroup()
for day in 1...4 {
// Set up the URL request
let endpoint = "https://sample.com/api/info/?date=2020-22-\(day)"
guard let url = URL(string: endpoint) else {
print("Error: cannot create URL")
continue
}
// make the request
group.enter()
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
defer { group.leave() }
if let error = error { print(error); return }
// parse the result as JSON, since that's what the API provides
do {
let sample = try JSONDecoder().decode([Sample].self, from: data!)
totalTemperature += sample.temperature
} catch {
print(error)
}
}
task.resume()
}
group.notify(queue: .main) {
print(totalTemperature)
}
}

Swift after json parsing variables are assigned to their initial values

I'm new to swift i am sorry if this is a stupid question
I am trying to expand my knowledge in macOS development and i am trying out new things
i am parsing a json file from an url
it works fine in the do{}catch{} brackets however, i want to use what i get from the json data in other parts of the program.
i created some variables to store the values.
However, they go back to their initial value once the do{}catch{} execution is done
how can i store the values I got
#IBAction func buttonPressed(_ sender: Any) {
var summonerNameGlobal: String = ""
var summonerIdGlobal: String = ""
var summonerPuuidGlobal: String = ""
var summonerAccountIdGlobal: String = ""
let jsonString = "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/john?api_key=\(apiKey)"
guard let url = URL(string: jsonString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {return}
DispatchQueue.main.async {
do {
let summoner = try JSONDecoder().decode(SummonerInfo.self, from: data)
self.summonerIdLabel.stringValue = summoner.id
summonerNameGlobal = summoner.name
summonerIdGlobal = summoner.id
summonerAccountIdGlobal = summoner.accountId
summonerPuuidGlobal = summoner.puuid
} catch {
print(error)
}
}
}.resume()
print(summonerNameGlobal)
print(summonerPuuidGlobal)
print(summonerIdGlobal)
print(summonerAccountIdGlobal)
}
They are not going to default again but you are checking them before they are being set ... because async function take some time to get response from server but your print statements run immediately
What you can do is to check values once they are set
func callApi(completion: #escaping (SummonerInfo?)->Void){
let jsonString = "https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/john?api_key=\(apiKey)"
guard let url = URL(string: jsonString) else {return}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {return}
DispatchQueue.main.async {
do {
let summoner = try JSONDecoder().decode(SummonerInfo.self, from: data)
completion(summoner)
} catch {
completion(nil)
print(error)
}
}
}.resume()
}
#IBAction func buttonPressed(_ sender: Any) {
callApi { [weak self] info in
if let getInfo = info {
print(getInfo.name)
print(getInfo.id)
print(getInfo.accountId)
print(getInfo.puuid)
} else {
print("data is nil")
}
}
}

Data tasks outside ViewController

I'm gonna start with I'm currently learning swift + iOS so I'm by no means an experienced developer or one for that matter.
My goal is to separate any network calls that are currently done in my view controller to a dedicated class outside of it.
In this view controller i have a IBAction with the following code inside of it:
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
session.dataTask(with: loginRequest) {
(data, response, error) in
guard let _ = response, let data = data else {return}
do {
let apiData = try NetworkManager.shared.decoder.decode(ApiData.self, from: data)
let token = apiData.data?.token
let saveToken: Bool = KeychainWrapper.standard.set(token!, forKey: "token")
DispatchQueue.main.async {
self.showOrHideActivityIndicator(showOrHide: false)
self.showHomeScreen()
}
} catch let decodeError as NSError {
print("Decoder error: \(decodeError.localizedDescription)\n")
return
}
}.resume()
What I want, or I think I want to achieve is something like this:
let apiData = "somehow get it from outside"
Then when apiData has info stored in it, execute this next bit of code:
let token = apiData.data?.token
let saveToken: Bool = KeychainWrapper.standard.set(token!, forKey: "token")
DispatchQueue.main.async {
self.showOrHideActivityIndicator(showOrHide: false)
self.showHomeScreen()
}
How would I achieve this? Thank you.
You can try
class API {
static func userLoginWith(email:String,password:String,completion:#escaping(_ token:String?) -> ()) {
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
session.dataTask(with: loginRequest) {
(data, response, error) in
guard let _ = response, let data = data else { completion(nil) ; return }
do {
let apiData = try NetworkManager.shared.decoder.decode(ApiData.self, from: data)
completion(apiData.data?.token)
} catch {
print("Decoder error: ",error")
completion(nil)
}
}.resume()
}
}
Inside the VC
API.userLoginWith(email:<##>,password:<##>) { (token) in
if let token = token {
let saveToken: Bool = KeychainWrapper.standard.set(token!, forKey: "token")
DispatchQueue.main.async {
self.showOrHideActivityIndicator(showOrHide: false)
self.showHomeScreen()
}
}
}