I am attempting to create an app in SwiftUI using GitHub's REST API. I am attempting to only retrieve only the login name and profile picture of a given user's followers and then populate a List.
FollowersView.swift
import SwiftUI
struct Follower: Codable, Hashable {
public var login: String
public var avatar_url: String
}
struct Response: Codable {
var followers: [Follower] = [Follower]()
}
struct FollowersView: View {
#EnvironmentObject var followerInfo: FollowerInfo
#State var followers: [Follower] = [Follower]()
init() {
UINavigationBar.appearance().largeTitleTextAttributes = [.foregroundColor: UIColor.white]
}
var body: some View {
NavigationView {
ZStack {
Color.black.edgesIgnoringSafeArea(.all)
List(followers, id: \.self) { follower in
HStack(spacing: 10) {
Image(decorative: "\(follower.avatar_url).png")
.resizable()
.frame(width: 75, height: 75)
HStack(spacing: 5) {
Image(systemName: "person")
Text("\(follower.login)").fontWeight(.heavy)
}
}
}
.onAppear(perform: loadData)
}
.navigationBarTitle("\(followerInfo.followerUsername)")
}
}
func loadData() {
guard let url = URL(string: "https://api.github.com/users/\(followerInfo.followerUsername)/followers") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
self.followers = decodedResponse.followers
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown Error")")
}.resume()
}
}
struct FollowersView_Previews: PreviewProvider {
static var previews: some View {
FollowersView()
}
}
The code gets to print("Fetch failed: \(error?.localizedDescription ?? "Unknown Error")") and prints "Unknown Error" before crashing. Upon inspecting the data that comes back, it comes up with nothing, at least not that I can tell anyway. (I'm not entirely accustomed to the Xcode debugger). I double checked the API response in a browser and the fields in the response in the browser and the names of the properties in the Codable struct match. So, I'm not exactly sure what's going on here. Any suggestions on how I can fix this issue?
If I understood your problem correctly. Update your Codable as shown below:
import Foundation
// MARK: - FollowerElement
struct FollowerElement: Codable {
let login: String
let id: Int
let nodeID: String
let avatarURL: String
let gravatarID: String
let url, htmlURL, followersURL: String
let followingURL, gistsURL, starredURL: String
let subscriptionsURL, organizationsURL, reposURL: String
let eventsURL: String
let receivedEventsURL: String
let type: String
let siteAdmin: Bool
enum CodingKeys: String, CodingKey {
case login, id
case nodeID = "node_id"
case avatarURL = "avatar_url"
case gravatarID = "gravatar_id"
case url
case htmlURL = "html_url"
case followersURL = "followers_url"
case followingURL = "following_url"
case gistsURL = "gists_url"
case starredURL = "starred_url"
case subscriptionsURL = "subscriptions_url"
case organizationsURL = "organizations_url"
case reposURL = "repos_url"
case eventsURL = "events_url"
case receivedEventsURL = "received_events_url"
case type
case siteAdmin = "site_admin"
}
}
typealias Follower = [FollowerElement]
You can remove properties you don't need from above code.
Now update your dataTask method
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("Fetch failed: \(error.localizedDescription)")
} else {
if let data = data {
do {
let follower = try JSONDecoder().decode(Follower.self, from: data)
DispatchQueue.main.async {
print(follower.count)
}
} catch {
print(error)
}
}
}
}.resume()
Related
My problem is - I'm building Weather App that displays 20 different cities at the same time (that's the task). I can do it with one city when i put it in guard let url = URL(string: ) directly like this (London)
struct Constants {
static let API_KEY = "<api-key>"
static let baseURL = "https://api.openweathermap.org/data/2.5/weather?appid=\(API_KEY)&units=metric&q=" // + cityName
}
class APICaller {
static let shared = APICaller()
func getData(completion: #escaping(Result<[WeatherDataModel], Error>) -> Void) {
guard let url = URL(string: "\(Constants.baseURL)London") else { return } // Here is the city i've put
let task = URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
guard let data = data, error == nil else {
return
}
do {
let results = try JSONDecoder().decode(MainWeatherDataModel.self, from: data)
completion(.success(results.results))
} catch {
completion(.failure(error))
}
}
task.resume()
}
}
My project contains CollectionView inside TableView. Parsed data filling Cells
But it's only one city showing in App. I need 19 more.
So my questions are: How can I implement different queries in URL or Is there a method do to multiple parsing?
Thank you
Here is a very basic example code, to fetch the weather for a number of cities using your modified setup. It shows how to implement different queries using the URL, as per the question.
Note, you should read about (and use) Swift async/await concurrency, to fetch
all the data concurrently.
struct Constants {
static let API_KEY = "api-key"
static let baseURL = "https://api.openweathermap.org/data/2.5/weather?appid=\(API_KEY)&units=metric&q="
}
class APICaller {
static let shared = APICaller()
// -- here
func getData(cityName: String, completion: #escaping(Result<[WeatherDataModel], Error>) -> Void) {
// -- here
guard let url = URL(string: (Constants.baseURL + cityName)) else { return }
URLSession.shared.dataTask(with: URLRequest(url: url)) { data, _, error in
guard let data = data, error == nil else { return }
do {
let results = try JSONDecoder().decode(MainWeatherDataModel.self, from: data)
// -- here
if let weather = results.weather {
completion(.success(weather))
} else {
completion(.success([]))
}
} catch {
completion(.failure(error))
}
}.resume()
}
}
struct ContentView: View {
#State var citiesWeather: [String : [WeatherDataModel]] = [String : [WeatherDataModel]]()
#State var cities = ["London", "Tokyo", "Sydney"]
var body: some View {
List(cities, id: \.self) { city in
VStack {
Text(city).foregroundColor(.blue)
Text(citiesWeather[city]?.first?.description ?? "no data")
}
}
.onAppear {
for city in cities {
fetchWeatherFor(city) // <-- no concurrency, not good
}
}
}
func fetchWeatherFor(_ name: String) {
APICaller.shared.getData(cityName: name) { result in
switch result {
case .success(let arr): citiesWeather[name] = arr
case .failure(let error): print(error) // <-- todo
}
}
}
}
struct WeatherDataModel: Identifiable, Decodable {
public let id: Int
public let main, description, icon: String
}
struct MainWeatherDataModel: Identifiable, Decodable {
let id: Int
let weather: [WeatherDataModel]?
}
hi everyone I'm newbie in Swift
I ask for help why the data is not displayed in List? Please help me a fix it.
I make a Model Data, and take a data from URl and parse it
My model:
struct ResponseData: Codable{
var userId: String
var id: String
var title: String
var body: String
}
My code in Content view:
import SwiftUI
struct ContentView: View {
#State var responseData = [ResponseData]()
var body: some View {
List(responseData, id: \.id ) { item in
Text("\(item.body)")
}
.task {
await loadData()
}
}
func loadData () async {
let urlString = "https://jsonplaceholder.typicode.com/posts"
guard let url = URL(string: urlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {return}
guard error == nil else {return}
do {
let postData = try JSONDecoder().decode(ResponseData.self, from: data)
} catch let error {
print(error)
}
}.resume()
}
}
There are many issues in the code.
The most significant ones are
In the struct userId and id are Int.
The JSON root object is an array, please note the starting [.
You don't update the model after receiving the data.
As you are using async/await anyway take full advantage of the pattern.
The JSON API returns posts, so how about to name the struct Post?
struct Post: Codable, Identifiable {
let userId: Int
let id: Int
let title: String
let body: String
}
struct ContentView : View {
#State var posts = [Post]()
var body : some View {
List(posts) { post in
Text(post.body)
}
.task {
do {
posts = try await loadData()
} catch {
print(error)
}
}
}
func loadData() async throws -> [Post] {
let urlString = "https://jsonplaceholder.typicode.com/posts"
let url = URL(string: urlString)!
let (data, _) = try await URLSession.shared.data(for: URLRequest(url: url))
return try JSONDecoder().decode([Post].self, from: data)
}
}
I am having issues trying to get this data. I heard there is a trick. Can anyone create a simple call to view the data from this api? Would truly appreciate it. Been trying for a week. I cant for the life of me get this simple api call to work.
http://api.citybik.es/v2/networks
Model.swift
import Foundation
// MARK: - Welcome
struct Dataset: Codable {
let networks: [Network]
}
// MARK: - Network
struct Network: Codable {
let company: [String]
let href, id: String
let location: Location
let name: String
}
// MARK: - Location
struct Location: Codable {
let city, country: String
let latitude, longitude: Double
}
Contentview.swift
import SwiftUI
struct ContentView: View {
#State var results = [Network]()
func loadData() {
guard let url = URL(string: "http://api.citybik.es/v2/networks") else {
print("Your API end point is Invalid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let response = try? JSONDecoder().decode([Network].self, from: data) {
DispatchQueue.main.async {
self.results = response
}
return
}
}
}.resume()
}
var body: some View {
List(results, id: \.name) { item in
VStack(alignment: .leading) {
Text("\(item.name)")
}
}.onAppear(perform: loadData)
}
}
copy the whole of the json from : "https://api.citybik.es/v2/networks"
into "https://app.quicktype.io/" and get the (correct) swift data structures from that.
Rename "Welcome" to "Response" and use that in your code.
use: "https://api.citybik.es/v2/networks" note the https.
EDIT: In your code:
struct ContentView: View {
#State var networks = [Network]()
var body: some View {
List(networks, id: \.id) { network in
VStack {
Text(network.name)
Text(network.location.city)
}
}.onAppear(perform: loadData)
}
func loadData() {
guard let url = URL(string: "https://api.citybik.es/v2/networks") else {
print("Your API end point is Invalid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let response = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
self.networks = response.networks
}
return
}
}
}.resume()
}
}
Once you have all the data structures,
and if you are using Swift 5.5 for ios 15 or macos 12, you can use something like this:
struct ContentView: View {
#State var networks = [Network]()
var body: some View {
List(networks, id: \.id) { network in
VStack {
Text(network.name)
Text(network.location.city)
}
}
.task {
let response: Response? = await fetchNetworks()
if let resp = response {
networks = resp.networks
}
}
}
func fetchNetworks<T: Decodable>() async -> T? {
let url = URL(string: "https://api.citybik.es/v2/networks")!
let request = URLRequest(url: url)
do {
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
// throw URLError(.badServerResponse) // todo
print(URLError(.badServerResponse))
return nil
}
let results = try JSONDecoder().decode(T.self, from: data)
return results
}
catch {
return nil
}
}
}
I am new to Swift and SwiftUI. I am currently teaching myself how to code (loving it!) through hackingwithswift.com I am currently on Day 60 and I am stuck and not sure what to do from here.
The challenge is to decode some information using Codable and populate SwiftUI.
I created a struct to match the JSON, but when I go to run the app, I keep getting my error "Fetch Failed: Unknown Error" and therefore my UI won't update.
Would someone glance at my code and provide any pointers on where I am going wrong and possibly why? Thank you so much for any suggestions and help, it is much appreciated! Code is posted below.
Cody
import SwiftUI
struct Response: Codable {
var results: [User]
}
struct User: Codable, Identifiable {
let id: String
let isActive: Bool
let name: String
let age: Int
let company: String
let email: String
let address: String
let about: String
let registered: String
let tags: [String]
struct FriendRole: Codable {
let id: String
let name: String
}
let friend: [FriendRole]
}
struct ContentView: View {
#State private var results = [User]()
var body: some View {
List(results, id: \.id) { item in
VStack(alignment: .leading) {
Text(item.name)
.font(.headline)
Text(item.address)
}
}
.onAppear(perform: loadData)
}
func loadData() {
guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
DispatchQueue.main.async {
self.results = decodedResponse.results
}
return
}
}
print("Fetch Failed: \(error?.localizedDescription ?? "Unkown Error").")
}.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I'm also new to swiftUI this is how I managed to make it work by using Observable Objects
Here's the structures Since in the json file there is a [ in the very beginning you do not have to create a struct that has a User array you could create a struct and then create a variable of that struct type as an array
here's how I did it
I created separate files for instance for the structures i had a different file for them
here's what I have for my structure file
import Foundation
struct User : Codable, Identifiable {
let id : String
let isActive : Bool
let name : String
let age : Int
let company : String
let email : String
let address : String
let about : String
let registered : String
let tags = [String]()
let friends = [Friends]()
}
struct Friends : Codable {
let id : String
let name : String
}
I created another file for the observable object class
class JsonChannel : ObservableObject {
#Published var retVal = [User]()
func getInfo () {
guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {return}
URLSession.shared.dataTask(with: url) { (data, resp, err) in
if let data = data {
DispatchQueue.main.async {
do {
self.retVal = try JSONDecoder().decode([User].self, from: data)
}
catch {
print(error)
}
}
}
}.resume()
}
}
and here's what i have for my contentView file
import SwiftUI
struct ContentView : View {
#ObservedObject var info = JsonChannel()
var body: some View {
VStack {
Button(action: {
self.info.getInfo()
}) {
Text("click here to get info")
}
List {
ForEach (self.info.retVal) { item in
VStack {
Text("\(item.name)")
Text("\(item.address)")
}
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I've been messing around with CoreData and this time I'm trying to save my downloaded JSON to core data. I don't get any error until I try to display the list and it would return empty.
Any suggestions would be much appreciated!
Model
struct ArticleData: Identifiable, Decodable {
let id : String
let type : String
let attributes: ArticleAttributee
struct ArticleAttributee: Codable {
let name: String
let card_artwork_url: String
...
}
AttributeArticle+CoreDataProperties.swift
extension AttributeArticle {
#nonobjc public class func fetchRequest() -> NSFetchRequest<AttributeArticle> {
return NSFetchRequest<AttributeArticle>(entityName: "AttributeArticle")
}
#NSManaged public var card_artwork_url: String?
#NSManaged public var content_type: String?
...
public var wrapperCard_artwork_url : String {
card_artwork_url ?? "Unknown"
}
...
}
Download JSOn and load to Core Data
class Article {
static func loadDataFromJSON(completion: #escaping ([ArticleData]) -> ()) {
let stringURL = "https://api.jsonbin.io/b/5ed679357741ef56a566a67f"
guard let url = URL(string: stringURL) else { return }
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) {
data, response, error in
guard let data = data else {
print("No data in response \(error?.localizedDescription ?? "No data response")")
return
}
if let decoderLoadedUser = try? JSONDecoder().decode([ArticleData].self, from: data) {
completion(decoderLoadedUser)
}
}.resume()
}
static func loadDataToCD(moc: NSManagedObjectContext) {
loadDataFromJSON { (articles) in
DispatchQueue.main.async {
var tempArticles = [AttributeArticle]()
for article in articles {
let newArticle = AttributeArticle(context: moc)
newArticle.name = article.attributes.name
newArticle.card_artwork_url = article.attributes.card_artwork_url
... so on
...
tempArticles.append(newArticle)
}
do {
try moc.save()
} catch let error {
print("Could not save data: \(error.localizedDescription)")
}
}
}
}
}
my list :
#Environment(\.managedObjectContext) var moc
#FetchRequest(entity: AttributeArticle.entity(), sortDescriptors: []) var articles: FetchedResults<AttributeArticle>
VStack {
List() {
ForEach(articles, id: \.id) { article in
NavigationLink(destination: ArticleDetailView(articles: article)){
ArticleRowView(articles: article)
}
}
}
}.onAppear {
if self.articles.isEmpty {
print("Articles is empty \(self.articles)")
Article.loadDataToCD(moc: self.moc)
}
Sorry for the long post and thank you for your helps!