Class 'JSONDecoder' requires that 'CoverImageView' conform to 'Decodable' [closed] - swift

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 days ago.
Improve this question
I know this question is very common among beginners but I will still ask: there are two files with super simple code. And there is nowhere to be wrong, but I was still mistaken. And I'm wrong about those things every time. Help me understand! Please!
File #1
import SwiftUI
struct CoverImageModel: Decodable, Identifiable {
let id: Int
let name: String
init(id: Int, name: String) {
self.id = id
self.name = name
}
}
And problem in File #2:
import Foundation
extension Bundle {
func decode (_ file: String) -> [CoverImageModel] {
//1. Locate JSON file
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in Bundle")
}
//2. Create a property for the data
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from Bundle")
}
//3. Create a decoder
let decoder = JSONDecoder()
//4. Create a property for the decoder data
guard let loaded = try? decoder.decode([CoverImageView].self, from: data) else {
fatalError("Failde to decode \(file) from Bundle")
}
//5. Return the ready-to-use data
return loaded
}
}
So, problem is Protocol Decode
I try to read Apple Swift Documentation, find solution on YouTube - I'm not understanding...

Related

Data is missing from API call to Unsplashed using Swift [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Problem:
I was following a tutorial and I cannot seem to get the data loaded when I get a API call from Unsplashed. I registered for an account and used my personal key.
I created my loadData function that should load the data from the API call:
func loadData() {
let key = "my key"
let url = "https://api.unsplash.com/photos/random/?count=30&client_id=\(key)"
let session = URLSession(configuration: .default)
session.dataTask(with: URL(string: url)!) { (data, _, error) in
guard let data = data else {
print("URLSession dataTask error", error ?? "nil")
return
}
print(data)
do{
let json = try JSONDecoder().decode([Photo].self,from: data)
print(json)
for photo in json {
DispatchQueue.main.async {
self.photoArray.append(photo)
}
}
}catch{
print("In error")
print(error.localizedDescription)
}
}.resume()
}
I present my data in the content view as follows:
import SwiftUI
struct ContentView: View {
#ObservedObject var randomImages = UnsplashData()
var body: some View {
Text("Hello, world!")
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I print the data before I use the JSON decoder and there seems to be data there, but when I go to get the JSON it states this error:
The data couldn’t be read because it is missing.
So is it the way I am using the API key? Or something else?
The photo structure is as follows:
struct Photo: Identifiable, Decodable {
var id: String
var alt_description: String
var urls: [String: String]
}
It's not the data that you're receiving, it's how you're decoding it that seems to be an issue.
For example, this simple playground example works just fine...
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
struct Sources: Decodable {
let raw: String
let full: String
let regular: String
let small: String
let thumbnail: String
}
struct Photo: Decodable {
let urls: [Sources]
}
let key = "don't post this, that's a bad idea"
let url = "https://api.unsplash.com/photos/random/?count=30&client_id=\(key)"
let session = URLSession(configuration: .default)
session.dataTask(with: URL(string: url)!) { (data, _, error) in
guard let data = data else {
print("URLSession dataTask error", error ?? "nil")
return
}
print(String(data: data, encoding: .utf8))
do{
let json = try JSONDecoder().decode([Photo].self,from: data)
print(json)
}catch{
print("In error")
print(error.localizedDescription)
}
}.resume()
If you change print(error.localizedDescription) to print(error) you'll generally get a more accurate description of the error

Fetching and decoding unkwown error in Swift [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to fetch the data and decode it into structs, and then display that data in a list.
I used quicktype.io to parse JSON to Swift. This part seems to be okay.
struct Response: Codable {
var results: [User]
}
struct User: Codable {
let id: String
let isActive: Bool
let name: String
let age: Int
let company, email, address, about: String
let registered: Date
let tags: [String]
let friends: [Friend]
}
struct Friend: Codable {
let id, name: String
}
This is the rest of the code, where I try to decode the data(where the error occurs). Here is a link to the JSON.
struct ContentView: View {
#State private var users = [User]()
var body: some View {
List {
ForEach(users, id: \.id) { user in
Text(user.name)
}
}.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) {
// we have good data – go back to the main thread
DispatchQueue.main.async {
// update our UI
print(decodedResponse.results)
users = decodedResponse.results
}
// everything is good, so we can exit
return
}
}
// if we're still here it means there was a problem
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}
You have to decode on type [User] not Response. Look at the response and you'll see that the top-level JSON is an Array, not a Dictionary. Also, update your code to get meaningful error messages. Use do try catch syntax instead of if let try?.
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 {
do {
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let users = try decoder.decode([User].self, from: data)
DispatchQueue.main.async {
print(users)
self.users = users
}
} catch {
print(error)
}
} else {
// if we're still here it means there was a problem
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}
}.resume()
}
Update: Also, need to add dateDecodingStrategy to make the decoding work correctly.

how to save my image into a database using sqlite? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am making an app where you can post an image and display it on another page. I want to save it to a database but I don't know the best way to do it.
you can save your image in document folder by using
func saveImage(image: UIImage) -> Bool {
guard let data = UIImageJPEGRepresentation(image, 1) ?? UIImagePNGRepresentation(image) else {
return false
}
guard let directory = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) as NSURL else {
return false
}
do {
try data.write(to: directory.appendingPathComponent("fileName.png")!)
return true
} catch {
print(error.localizedDescription)
return false
}
}
and you can get it your image with this method :
func getSavedImage(named: String) -> UIImage? {
if let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) {
return UIImage(contentsOfFile: URL(fileURLWithPath: dir.absoluteString).appendingPathComponent(named).path)
}
return nil
}
You can use Core data in swift to save Image.
Core Data is an object graph and persistence framework provided by Apple in the macOS and iOS operating systems.
By using Core data you can access sqlite database easily.
To save image in Sqlite Using Core Data See saving-picked-image-to-coredata
you save your image in device and save path of that image in Sqlite.
this link for how to save image in device Saving image and then loading it in Swift (iOS)

Cannot convert value of type 'NSData' to type 'Date' in coercion in json work? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
func jsonDateCalling(){
//Json Serilizarions
let jsonUrl = URL(string: "http://assetlinkasia.no-ip.biz:8001/hf_tracker/api/history.php?accesskey=12345&Vehilce=1618&FromDate=2018-05-10 13:11&ToDate=2018-05-14 12:11")
if let url = jsonUrl{
let data = NSData(contentsOf: url)
if let data = data{
do{
let jsonObject = try JSONSerialization.jsonObject(with: data as Date, options: .allowFragments)
if let object = jsonObject as? [NSString: AnyObject]{
if let allDevices = object["data"] as? [[NSString: AnyObject]]{
print("Successfull")
self.tableArray = allDevices
self.searchTextTableview.reloadData()
}
}
}catch{
print("Error Eccurred")
}
}
}
}
This is a work for json but i am facing "Cannot convert value of type 'NSData' to type 'Date' in coercion" how can i solve. and i am thinking this error for date parametter
1- Replace this
let jsonObject = try JSONSerialization.jsonObject(with: data as Date, options: .allowFragments)
with
let jsonObject = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
it's a Data object not Date
2- no need for fragments it can be
let jsonObject = try JSONSerialization.jsonObject(with: data as Data, options: [])
if let object = jsonObject as? [NSString: Any]
3- this line
let data = NSData(contentsOf: url)
blocks main thread consider using URLSession or Alamofire

Swift 3 error: Type 'Any' has no subscript members

So I know this question has been asked and answered numerous times before, but I just migrated my project to Swift 3 and Im getting a ton of these errors in my code that parses JSON and I couldn't quite find answers that made me understand how to resolve my specific issue.
guard let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] else {
return
}
guard let responseData = result["Data"] else { return }
guard let userData = responseData["UserProfile"] else { return }
var userProfileFieldsDict = [String: String]()
if let sessionToken = userData!["CurrentSessionToken"] as? NSString {
userProfileFieldsDict["sessionToken"] = String(sessionToken)
}
}
The if let sessionToken line throws the aforementioned error, but not quite sure how you're supposed to deal with this in Swift 3? Could someone explain and suggest a best practice fix?
Thanks a bunch!
If responseData["UserProfile"] is also a dictionary you'll probably want to cast it as such in you guard by saying guard let userData = responseData["UserProfile"] as? [String : AnyObject] else { return }. I suspect this will solve your problem.
As a small aside, you don't need to force unwrap userData in your if let, because you've already unwrapped it in the guard.