I'm trying to fetch data from an API but I can't get it right and I don't know the issue here:
struct BTCData : Codable {
let close : Double
let high : Double
let low : Double
private enum CodingKeys : Int, CodingKey {
case close = 3
case high = 4
case low = 5
}
}
func fetchBitcoinData(completion: #escaping (BTCData?, Error?) -> Void) {
let url = URL(string: "https://api.bitfinex.com/v2/candles/trade:30m:tBTCUSD/hist")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
if let bitcoin = try JSONDecoder().decode([BTCData].self, from: data).first {
print(bitcoin)
completion(bitcoin, nil)
}
} catch {
print(error)
}
}
task.resume()
}
I'd like to be able to access close in every dict and iterate like that:
var items : BTCData!
for idx in 0..<15 {
let diff = items[idx + 1].close - items[idx].close
upwardMovements.append(max(diff, 0))
downwardMovements.append(max(-diff, 0))
}
I get nil. I don't understand how to decode this kind of API where I need to iterate something which is not inside another dict.
EDIT: The above was solved and I'm now struggling to use [BTCData] in another function.
I am trying to use it here :
func fetchBitcoinData(completion: #escaping ([BTCData]?, Error?) -> Void) {
let url = URL(string: "https://api.bitfinex.com/v2/candles/trade:30m:tBTCUSD/hist")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {
completion(nil, error ?? FetchError.unknownNetworkError)
return
}
do {
let bitcoin = try JSONDecoder().decode([BTCData].self, from: data); completion(bitcoin, nil)
//let close52 = bitcoin[51].close
//print(bitcoin)
//print(close52)
} catch let parseError {
completion(nil, parseError)
}
}
task.resume()
}
class FindArray {
var items = [BTCData]()
func findArray() {
let close2 = items[1].close
print(close2)
}
}
fetchBitcoinData() { items, error in
guard let items = items,
error == nil else {
print(error ?? "Unknown error")
return
}
let call = FindArray()
call.items = items
call.findArray()
}
EDIT 2: Solved it with [BTCData](). var items : [BTCData] = [] works too
To decode an array of arrays into a struct with Decodable you have to use unkeyedContainer. Since there is no dictionary CodingKeys are useless.
struct BTCData : Decodable {
let timestamp : Int
let open, close, high, low, volume : Double
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
timestamp = try container.decode(Int.self)
open = try container.decode(Double.self)
close = try container.decode(Double.self)
high = try container.decode(Double.self)
low = try container.decode(Double.self)
volume = try container.decode(Double.self)
}
}
You don't have to change your JSONDecoder() line.
...
if let bitcoin = try JSONDecoder().decode([BTCData].self, from: data).first {
print(bitcoin)
completion(bitcoin, nil)
}
Just by adding two lines it's even possible to decode the timestamp into a Date value
struct BTCData : Decodable {
let timestamp : Date
let open, close, high, low, volume : Double
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
timestamp = try container.decode(Date.self)
...
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .millisecondsSince1970
if let bitcoin = try decoder.decode([BTCData].self, from: data).first {
print(bitcoin)
completion(bitcoin, nil)
}
To decode the array and get a value at specific index
do {
let bitcoins = try JSONDecoder().decode([BTCData].self, from: data)
let close52 = bitcoins[51].close
print(close52)
...
You need to use JSONSerialization and cast to [[NSNumber]] to get the result needed
UPDATE
Checking this https://docs.bitfinex.com/v2/reference#rest-public-candles I think this is what you are searching for
Try using this
func fetchBitcoinData(completion: #escaping ([BTCData]?, Error?) -> Void) {
let url = URL(string: "https://api.bitfinex.com/v2/candles/trade:30m:tBTCUSD/hist")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else { return }
do {
if let array = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[NSNumber]]{
var arrayOfCoinData : [BTCData] = []
for currentArray in array{
arrayOfCoinData.append(BTCData(close: currentArray[2].doubleValue, high: currentArray[3].doubleValue, low: currentArray[4].doubleValue))
}
debugPrint(arrayOfCoinData)
completion(arrayOfCoinData, nil)
}
} catch {
print(error)
completion(nil, error)
}
}
task.resume()
}
Log Result
[BitcoinApiExample.BTCData(close: 7838.8999999999996,...]
Related
I'm trying to fetch movie data using The Movie Database API and display them on a table view, but my code isn't actually getting any data.
class MovieData: NSObject, Decodable {
var movies: [Movie]?
private enum CodingKeys: String, CodingKey {
case movies = "results"
}
}
I think it has something to do with my coding keys because the movie data I want to retrieve are within an array. Seen here. But I'm a little confused with how Codable works.
class Movie: NSObject, Decodable {
var title: String?
var year: String?
var rate: Double?
var posterImage: String?
var overview: String?
private enum MovieKeys: String, CodingKey {
case title
case overview
case releaseDate = "release_date"
case rate = "vote_average"
case posterImage = "poster_path"
}
required init(from decoder: Decoder) throws {
let movieContainer = try decoder.container(keyedBy: MovieKeys.self)
// Get movie info
title = try movieContainer.decode(String.self, forKey: .title)
overview = try movieContainer.decode(String.self, forKey: .overview)
posterImage = try movieContainer.decode(String.self, forKey: .posterImage)
rate = try movieContainer.decode(Double.self, forKey: .rate)
// releaseDate = try movieContainer.decode(String.self, forKey: .releaseDate)
}
}
This is what I'm using to make the api call, so when the user loads into the view the API will fetch movie data and display it on a cell.
override func viewDidLoad() {
super.viewDidLoad()
let requestURL = URL(string: "https://api.themoviedb.org/3/movie/popular?api_key=\(apiKey)&language=en-US&page=1")
if let requestURL = requestURL {
Task {
do {
let (data, response) = try await URLSession.shared.data(from: requestURL)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw MovieListError.invalidServerResponse
}
let decoder = JSONDecoder()
let movie = try decoder.decode(Movie.self, from: data)
print(data)
print(movie)
}
catch {
print(error)
}
}
}
}
It seems your are trying to decode a wrong object. It should be MovieData.self not Movie.self. And then you can iterate over the array of Movie.
override func viewDidLoad() {
super.viewDidLoad()
let requestURL = URL(string: "https://api.themoviedb.org/3/movie/popular?api_key=\(apiKey)&language=en-US&page=1")
if let requestURL = requestURL {
Task {
do {
let (data, response) = try await URLSession.shared.data(from: requestURL)
guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
throw MovieListError.invalidServerResponse
}
let decoder = JSONDecoder()
// change Movie.self to MovieData.self
let movies = try decoder.decode(MovieData.self, from: data)
print(data)
print(movies)
}
catch {
print(error)
}
}
}
}
Hello i am trying to get result based on a result from another api.The getLatest function is going to get the latest object and will return the number then i want to generate a list of urls with the latest number and then sequentially get the data in the function getXKCDData.How can i achieve this.The dispatchgroup i have on there works sometimes but doesnt work all the time because generateUrlList is called before getting the latest number and it generate the wrong url.Which causes The operation couldn’t be completed. (XKCD_Comics.NetworkError error 1.) error.How can i achieve this.
final class NetworkManager {
public static var shared = NetworkManager()
private let sessions = URLSession.shared
private func generateUrlList(latestXKCD: Int) -> [String] {
print("Here at generateUrlList")
var urls = [String]()
for i in latestXKCD-100...latestXKCD{
let xkcd_url = "https://xkcd.com/\(i)/info.0.json"
urls.append(xkcd_url)
}
return urls
}
private func getLatest(completion: #escaping(Int) -> ()){
print("Here at get latest")
guard let url = URL(string: "https://xkcd.com/info.0.json") else { return }
let task = sessions.dataTask(with: url) { data, response, error in
guard let jsonData = data else { return }
do {
let decoder = JSONDecoder()
let response = try decoder.decode(Comics.self, from: jsonData)
completion(response.num)
}catch {
completion(0)
}
}
task.resume()
}
public func getXKCDData(completion: #escaping(Result<Comics,NetworkError>) -> Void){
let group = DispatchGroup()
var latestID = 0
group.enter()
self.getLatest { (result) in
latestID = result
group.leave()
}
let urlList = generateUrlList(latestXKCD: latestID)
print(urlList)
print("Here at getXKCDData")
for url in urlList {
group.enter()
guard let url = URL(string: url) else {
completion(.failure(.InvalidURL))
return
}
let task = sessions.dataTask(with: url) { data, response, error in
guard let jsonData = data else {
completion(.failure(.NoDataAvailable))
return
}
do {
let decoder = JSONDecoder()
let response = try decoder.decode(Comics.self, from: jsonData)
completion(.success(response))
group.leave()
}catch {
completion(.failure(.CanNotProcessData))
}
}
task.resume()
}
}
}
I'm trying to play around with a COVID dataset from Github (link in code below) but when I run the code nothing appears in the console. There are no errors appearing.
Can anyone advise on whats wrong here? Thanks in advance!
struct country: Decodable {
var location: String
var new_cases: Double
var people_fully_vaccinated: Double
}
func getJSON(){
guard let url = URL(string: "https://raw.githubusercontent.com/owid/covid-19-data/68c39808d445fe90b1fe3d57b93ad9be20f796d2/public/data/latest/owid-covid-latest.json") else{
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request){ (data, response, error) in
if let error = error{
print(error.localizedDescription)
return
}
guard let data = data else{
return
}
let decoder = JSONDecoder()
guard let decodedData = try? decoder.decode([country].self, from: data) else{
return
}
let countries = decodedData
for country in countries{
print (country.location)
}
}.resume()
}
getJSON()
You need
struct Root: Decodable {
var location: String
var new_cases: Double? // make it optional as it has some objects with nil
var people_fully_vaccinated: Double? // make it optional as it has some objects with nil
}
With
do {
let res = try decoder.decode([String:Root].self, from: data)
let locations = Array(res.values).map { $0.location }
print(locations)
}
catch {
print(error)
}
My JSONDecoder().decode can't decode data to json format, because server response has Content-Type like this "* \ *;charset=utf8".
What I have to do in this situation? Any ideas? API link
My code:
private static let livePhotoUrlString = "https://m1.kappboom.com/livewallpapers/info?o=0&v=575"
static func getLivePhotos(completionHandler: #escaping (([LivePhoto]) -> Void)) {
guard let livePhotoUrl = URL(string: livePhotoUrlString) else { return }
let semaphore = DispatchSemaphore(value: 0)
URLSession.shared.dataTask(with: livePhotoUrl) { (data, response, error) in
do {
guard let data = data else { return }
let livePhotos = try JSONDecoder().decode([LivePhoto].self, from: data)
completionHandler(livePhotos)
} catch {
completionHandler([])
}
semaphore.signal()
}.resume()
semaphore.wait()
}
My entity (LivePhoto):
class LivePhoto: Decodable {
init(smallUrl: String, largeUrl: String, movieUrl: String, id: Int, isLocked: Bool, promotionalUnlock: Bool) {
self.smallUrl = smallUrl
self.largeUrl = largeUrl
self.movieUrl = movieUrl
self.id = id
self.isLocked = isLocked
self.promotionalUnlock = promotionalUnlock
}
var smallUrl: String
var largeUrl: String
var movieUrl: String
var id: Int
var isLocked: Bool
var promotionalUnlock: Bool
}
Response headers:
Correct response (another API):
The error is not related to the content type.
Rather than ignoring the error in the catch block print it, decoding errors are very descriptive.
} catch {
print(error)
completionHandler([])
}
It states
keyNotFound(CodingKeys(stringValue: "smallUrl", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"smallUrl\", intValue: nil) (\"smallUrl\").", underlyingError: nil))
You can see immediately that the key is small_url and your struct member is smallUrl.
The easiest solution is to add the convertFromSnakeCase key decoding strategy
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let livePhotos = try decoder.decode([LivePhoto].self, from: data)
And you don't need the init method in the class. Declare it as struct with constant members
struct LivePhoto: Decodable {
let smallUrl, largeUrl, movieUrl: String
let id: Int
let isLocked: Bool
let promotionalUnlock: Bool
}
And please delete this horrible semaphore. As you are using a completion handler anyway it's pointless.
Are you sure that is the problem, to me it looks like you need to define coding keys for your struct
enum CodingKeys: String, CodingKey {
case smallUrl = "small_url"
case largeUrl = "large_url"
case movieUrl = "movie_url"
case isLocked = "is_locked"
case promotionalUnlock = "promotional_unlock"
case id
}
You need to use key names as they are in json , or write an enum with the converted names , but better to use convertFromSnakeCase
func getLivePhotos(completionHandler: #escaping (([LivePhoto]) -> Void)) {
guard let livePhotoUrl = URL(string: livePhotoUrlString) else { return }
URLSession.shared.dataTask(with: livePhotoUrl) { (data, response, error) in
print(data)
do {
guard let data = data else { return }
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let livePhotos = try dec.decode([LivePhoto].self, from: data)
completionHandler(livePhotos)
} catch {
print(error)
completionHandler([])
}
}.resume()
}
}
struct LivePhoto: Codable {
let id: Int
let smallUrl, largeUrl: String
let movieUrl: String
let isLocked, promotionalUnlock: Bool
}
Also it's a best practice to always print(error) inside the catch block , so you can know the error and fix , here there is no place for semaphores , it's only the job of the completion , also you may show an activity indicator until the request finishes as a better UX
I am using swift 3.0 and have created a function that returns an Array of Integers. The arrays of Integers are very specific and they are gotten from a database therefore the HTTP call is asynchronous . This is a function because I use it in 3 different controllers so it makes sense to write it once . My problem is that the Async code is returned after the return statement at the bottom therefore it is returning nil . I have tried the example here Waiting until the task finishes however it is not working mainly because I need to return the value . This is my code
func ColorSwitch(label: [UILabel]) -> [Int] {
for (index, _) in label.enumerated() {
label[index].isHidden = true
}
// I need the value of this variable in the return
// statement after the async is done
var placeArea_id = [Int]()
let urll:URL = URL(string:ConnectionString+"url")!
let sessionn = URLSession.shared
var requestt = URLRequest(url: urll)
requestt.httpMethod = "POST"
let group = DispatchGroup()
group.enter()
let parameterr = "http parameters"
requestt.httpBody = parameterr.data(using: String.Encoding.utf8)
let task = sessionn.dataTask(with:requestt, completionHandler: {(data, response, error) in
if error != nil {
print("check check error")
} else {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
DispatchQueue.main.async {
if let Profiles = parsedData?["Results"] as? [AnyObject] {
if placeArea_id.count >= 0 {
placeArea_id = [Int]()
}
for Profiles in Profiles {
if let pictureS = Profiles["id"] as? Int {
placeArea_id.append(pictureS)
}
}
}
group.leave()
}
} catch let error as NSError {
print(error)
}
}
})
task.resume()
group.notify(queue: .main) {
// This is getting the value however can't return it here since it
// expects type Void
print(placeArea_id)
}
// this is nil
return placeArea_id
}
I already checked and the values are returning inside the async code now just need to return it any suggestions would be great .
You will want to use closures for this, or change your function to be synchronous.
func ColorSwitch(label: [UILabel], completion:#escaping ([Int])->Void) {
completion([1,2,3,4]) // when you want to return
}
ColorSwitch(label: [UILabel()]) { (output) in
// output is the array of ints
print("output: \(output)")
}
Here's a pretty good blog about closures http://goshdarnclosuresyntax.com/
You can't really have your function return a value from an asynchronous operation within that function. That would defeat the purpose of asynchronicity. In order to pass that data back outside of your ColorSwitch(label:) function, you'll need to also have it accept a closure that will be called on completion, which accepts an [Int] as a parameter. Your method declaration will need to look something like this:
func ColorSwitch(label: [UILabel], completion: #escaping ([Int]) -> Void) -> Void {
for (index, _) in label.enumerated() {
label[index].isHidden = true
}
var placeArea_id = [Int]()
let urll:URL = URL(string:ConnectionString+"url")!
let sessionn = URLSession.shared
var requestt = URLRequest(url: urll)
requestt.httpMethod = "POST"
let group = DispatchGroup()
group.enter()
let parameterr = "http parameters"
requestt.httpBody = parameterr.data(using: String.Encoding.utf8)
let task = sessionn.dataTask(with:requestt, completionHandler: {(data, response, error) in
if error != nil {
print("check check error")
} else {
do {
let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
DispatchQueue.main.async {
if let Profiles = parsedData?["Results"] as? [AnyObject] {
if placeArea_id.count >= 0 {
placeArea_id = [Int]()
}
for Profiles in Profiles {
if let pictureS = Profiles["id"] as? Int {
placeArea_id.append(pictureS)
}
}
}
group.leave()
completion(placeArea_id) // This is effectively your "return"
}
} catch let error as NSError {
print(error)
}
}
})
task.resume()
}
Later on, you can call it like this:
ColorSwitch(label: []) { (ids: [Int]) in
print(ids)
}