trying to fetch some data with dataTaskPublisher. however, constantly receive following log. it works every once in a while and not sure what's the difference. change URL does not make a difference. still only occasionally succeed the request.
Test2: receive subscription: (TryMap)
Test2: request unlimited
Test2: receive cancel
class DataSource: NSObject, ObservableObject {
var networker: Networker = Networker()
func fetch() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {
fatalError("Invalid URL")
}
networker.fetchUrl(url: url)
}
}
class Networker: NSObject, ObservableObject {
var pub: AnyPublisher<Data, Error>? = nil
var sub: Cancellable? = nil
var data: Data? = nil
var response: URLResponse? = nil
func fetchUrl(url: URL) {
guard let url = URL(string: "https://apple.com") else {
return
}
pub = URLSession.shared.dataTaskPublisher(for: url)
.receive(on: DispatchQueue.main)
.tryMap() { data, response in
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw URLError(.badServerResponse)
}
return data
}
.print("Test2")
.eraseToAnyPublisher()
sub = pub?.sink(
receiveCompletion: { completion in
switch completion {
case .finished:
break
case .failure(let error):
fatalError(error.localizedDescription)
}
},
receiveValue: {
print($0)
}
)
}
add .store(in: &subscriptions)
Related
I am trying to understand what is going on in my code here.
I have a simple API call to open weahter API and that whenever the user taps the UIButton, it should call the api and get the data back from open weather.
Everything works as intended however, when I have my UIButton pressed, the print statement executed first before the Task closure. I'm trying to understand the race condition here
This is my code in viewController:
#IBAction func callAPIButton(_ sender: UIButton) {
Task {
let weatherData = await weatherManager.fetchWeather(cityName: "Seattle")
}
}
Here's the code for fetching the API:
struct WeatherManager{
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?appid=someAPIKeyHere"
func fetchWeather(cityName: String) -> WeatherModel? {
let urlString = "\(weatherURL)&q=\(cityName)"
let requestResult = performRequest(urlString: urlString)
return requestResult
}
func performRequest(urlString: String) -> WeatherModel? {
var weatherResult : WeatherModel? = nil
if let url = URL(string: urlString){
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
if error != nil {
return
}
if let safeData = data {
weatherResult = parseJSON(weatherData: safeData)
}
})
task.resume()
}
return weatherResult
}
func parseJSON(weatherData: Data) -> WeatherModel?{
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(WeatherResponse.self, from: weatherData)
print("this is in decodedData: \(decodedData)")
let temp = decodedData.main.temp
let name = decodedData.name
let weather = WeatherModel(conditionId:300, cityName: name, temperature: temp)
return weather
} catch {
print("Something is wrong here: " + error.localizedDescription)
}
return nil
}
}
Here's my Model:
struct WeatherModel{
let conditionId: Int
let cityName: String
let temperature: Double
var temperatureString: String{
return String(format: "%.1f", temperature)
}
var conditionName: String {
switch conditionId {
case 200...232:
return "cloud.bolt"
case 300...321:
return "cloud.drizzle"
case 500...531:
return "cloud.rain"
case 600...622:
return "cloud.snow"
case 701...781:
return "cloud.fog"
case 800:
return "sun.max"
case 801...804:
return "cloud.bolt"
default:
return "cloud"
}
}
}
Desired result:
This is in weatherData: WeatherResponse(name: "Seattle", weather: [Awesome_Weather_App.WeatherAPI(description: "overcast clouds", icon: "04d")], main: Awesome_Weather_App.MainAPI(temp: 287.81, pressure: 1018.0, humidity: 44.0, temp_min: 284.91, temp_max: 290.42, feels_like: 286.48), sys: Awesome_Weather_App.SysAPI(sunrise: 1.6712886e+09, sunset: 1.6713243e+09))
This is what I am getting instead:
This is in weatherData: nil
this is in decodedData: WeatherResponse(name: "Seattle", weather: [Awesome_Weather_App.WeatherAPI(description: "overcast clouds", icon: "04d")], main: Awesome_Weather_App.MainAPI(temp: 287.81, pressure: 1018.0, humidity: 44.0, temp_min: 284.91, temp_max: 290.42, feels_like: 286.48), sys: Awesome_Weather_App.SysAPI(sunrise: 1.6712886e+09, sunset: 1.6713243e+09))
Thank you in advance
Everything works as intended
No, it doesn't. I don't know why you claim such a thing; your code isn't working at all.
The problem is that you are trying to return weatherResult from performRequest. But performRequest gets its weatherResult value asynchronously, so this attempt is doomed to failure; you will always be returning nil, because the return weatherResult happens before session.dataTask ever even starts to find out what weatherResult is.
You cannot just synchronously return the results of an asynchronous request. You have two basic options for asynchronous requests.
Use the older “completion handler” pattern with Result types:
struct WeatherManager {
let weatherURL = "https://api.openweathermap.org/data/2.5/weather"
let appId = "someAPIKeyHere"
func fetchWeather(
cityName: String,
completion: #escaping (Result<WeatherModel, Error>) -> Void
) {
guard var components = URLComponents(string: weatherURL) else {
completion(.failure(URLError(.badURL)))
return
}
components.queryItems = [
URLQueryItem(name: "appid", value: appId),
URLQueryItem(name: "q", value: cityName)
]
guard let url = components.url else {
completion(.failure(URLError(.badURL)))
return
}
performRequest(url: url, completion: completion)
}
func performRequest(
url: URL,
queue: DispatchQueue = .main,
completion: #escaping (Result<WeatherModel, Error>) -> Void
) {
let session = URLSession.shared // note, do not create a new URLSession for every request or else you will leak; use shared instance
let task = session.dataTask(with: url) { data, response, error in
guard
error == nil,
let data = data,
let response = response as? HTTPURLResponse,
200 ..< 300 ~= response.statusCode
else {
queue.async { completion(.failure(error ?? URLError(.badServerResponse))) }
return
}
do {
let weatherResult = try parseJSON(weatherData: data)
queue.async { completion(.success(weatherResult)) }
} catch {
queue.async { completion(.failure(error)) }
}
}
task.resume()
}
func parseJSON(weatherData: Data) throws -> WeatherModel {
let decoder = JSONDecoder()
let response = try decoder.decode(WeatherResponse.self, from: weatherData)
print("this is in decodedData: \(response)")
return WeatherModel(conditionId: 300, cityName: response.name, temperature: response.main.temp)
}
}
Then, rather than:
let weather = weatherManager.fetchWeather(cityName: …)
You would
weatherManager.fetchWeather(cityName: …) { result in
switch result {
case .failure(let error):
print(error)
case .success(let weather):
// do something with the `weather` object here
}
}
// note, do not do anything with `weather` here, because the above
// runs asynchronously (i.e., later).
Use the newer async-await pattern of Swift concurrency:
struct WeatherManager {
let weatherURL = "https://api.openweathermap.org/data/2.5/weather"
let appId = "someAPIKeyHere"
func fetchWeather(cityName: String) async throws -> WeatherModel {
guard var components = URLComponents(string: weatherURL) else {
throw URLError(.badURL)
}
components.queryItems = [
URLQueryItem(name: "appid", value: appId),
URLQueryItem(name: "q", value: cityName)
]
guard let url = components.url else {
throw URLError(.badURL)
}
return try await performRequest(url: url)
}
func performRequest(url: URL) async throws -> WeatherModel {
let session = URLSession.shared // note, do not create a new URLSession for every request or else you will leak; use shared instance
let (data, response) = try await session.data(from: url)
guard
let response = response as? HTTPURLResponse,
200 ..< 300 ~= response.statusCode
else {
throw URLError(.badServerResponse)
}
return try parseJSON(weatherData: data)
}
func parseJSON(weatherData: Data) throws -> WeatherModel {
let decoder = JSONDecoder()
do {
let response = try decoder.decode(WeatherResponse.self, from: weatherData)
print("this is in decodedData: \(response)")
return WeatherModel(conditionId: 300, cityName: response.name, temperature: response.main.temp)
} catch {
print("Something is wrong here: " + error.localizedDescription)
throw error
}
}
}
And then you can do things like:
Task {
do {
let weather = try await weatherManager.fetchWeather(cityName: …)
// do something with `weather` here
} catch {
print(error)
}
}
Note, a few changes in the above unrelated to the asynchronous nature of your request:
Avoid creating URLSession instances. If you do, you need to remember to invalidate them. Instead, it is much easier to use URLSession.shared, eliminating this annoyance.
Avoid building URLs with string interpolation. Use URLComponents to build safe URLs (e.g., ones that can handle city names like “San Francisco”, with spaces in their names).
I have an API call that grabs json, but requires token authentication. Token auth works great, but when I try and pass the token along to the API function, it's coming back nil. I believe it's because Auth.auth().currentUser!.getIDToken(...) hasn't actually completed yet. Relevant code below... How do I modify this to
class SessionData : ObservableObject {
...
func token() -> String? {
var result: String? = nil
Auth.auth().currentUser!.getIDToken(completion: { (res, err) in
if err != nil {
print("*** TOKEN() ERROR: \(err!)")
} else {
print("*** TOKEN() SUCCESS: \(err!)")
result = res!
}
})
return result
}
...
}
class FetchPosts: ObservableObject {
#Published var posts = [Post]()
func load(api: Bool, session: SessionData) {
if api {
let url = URL(string: MyAPI.getAddress(token: session.token()!))!
URLSession.shared.dataTask(with: url) {(data, response, error) in
do {
if let postsData = data {
// 3.
let decodedData = try JSONDecoder().decode(Response.self, from: postsData)
DispatchQueue.main.async {
self.posts = decodedData.result
if decodedData.error != nil {
print("ERROR: \(decodedData.error!)")
session.json_error(error: decodedData.error!)
}
}
} else {
print("No data. Connection error.")
DispatchQueue.main.async {
session.json_error(error: "Could not connect to server, please try again!")
}
}
} catch {
print("* Error: \(error)")
}
}.resume()
} else {
let url = Bundle.main.url(forResource: "test", withExtension: "json")!
let data = try! Data(contentsOf: url)
let decoder = JSONDecoder()
if let products = try? decoder.decode([Post].self, from: data) {
self.posts = products
}
}
}
}
And this is how the .load function is called:
UserViewer(fetch: posts)
.transition(AnyTransition.slide)
.animation(.default)
.onAppear {
withAnimation{
posts.load(api: true, session: session)
}
}
.environmentObject(session)
Because getIDToken executes and returns asynchronously, you can't return directly from it. Instead, you'll need to use a callback function.
Here's a modification of your function:
func token(_ completion: #escaping (String?) -> ()) {
guard let user = Auth.auth().currentUser else {
//handle error
return
}
user.getIDToken(completion: { (res, err) in
if err != nil {
print("*** TOKEN() ERROR: \(err!)")
//handle error
} else {
print("*** TOKEN() SUCCESS: \(err!)")
completion(res)
}
})
}
Then, you can use it later on:
.onAppear {
session.token { token in
guard let token = token else {
//handle nil
return
}
withAnimation{
posts.load(api: true, session: session, token: token)
}
}
}
Modify your load to take a token parameter:
func load(api: Bool, session: SessionData, token: String) {
if api {
guard let url = URL(string: MyAPI.getAddress(token: token)) else {
//handle bad URL
return
}
Also, as you can see I'm doing in my code samples, I would try to get out of the habit of using ! to force unwrap optionals. If the optional is nil and you use !, your program will crash. Instead, familiarize yourself with guard let and if let and learn to handle optionals in a way that won't lead to a crash -- it's one of the great benefits of Swift.
I kind of wrote everything correctly and the code itself is working but it gives me an error Result of call to 'fetchPokemon()' is unused, what could be the problem here?
Hear is my code: ModelView class
import Foundation
import Combine
class NetworkManager: ObservableObject {
let baseuRL = "https://pokeapi.co/api/v2/pokemon"
#Published var pokemon: [Pokemon] = []
var error: Error?
var cancellables: Set<AnyCancellable> = []
func fetchPokemon() -> Future<[Pokemon], Error> {
return Future<[Pokemon], Error> { promice in
guard let url = URL(string: "\(self.baseuRL)") else {
return promice(.failure(ApiError.unknowed))
}
URLSession.shared.dataTaskPublisher(for: url)
.tryMap { (data, response) -> Data in
guard let http = response as? HTTPURLResponse,
http.statusCode == 200 else {
throw ApiError.responseError
}
return data
}
.decode(type: PokemonList.self, decoder: JSONDecoder())
.receive(on: RunLoop.main)
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
break
case .failure(let error):
print(error)
}
}, receiveValue: {
promice(.success($0.results))
})
.store(in: &self.cancellables)
}
}
struct ContentView: View {
#StateObject var net = NetworkManager()
var body: some View {
List(net.pokemon, id: \.self) { pokemon in
Text(pokemon.name)
}.onAppear {
net.fetchPokemon()
}
}
}
Your fetchPokemon function returns a Future, but you're not doing anything with it -- that's why you're getting the unused error.
Also, in that function, you're returning your promise, but not doing anything with the results. So, you need to handle the Future and do something with those results.
It might look something like the following:
class NetworkManager: ObservableObject {
let baseuRL = "https://pokeapi.co/api/v2/pokemon"
#Published var pokemon: [Pokemon] = []
var error: Error?
var cancellables: Set<AnyCancellable> = []
//New function here:
func runFetch() {
fetchPokemon().sink { (completion) in
//handle completion, error
} receiveValue: { (pokemon) in
self.pokemon = pokemon //do something with the results from your promise
}.store(in: &cancellables)
}
private func fetchPokemon() -> Future<[Pokemon], Error> {
return Future<[Pokemon], Error> { promice in
guard let url = URL(string: "\(self.baseuRL)") else {
return promice(.failure(ApiError.unknowed))
}
URLSession.shared.dataTaskPublisher(for: url)
.tryMap { (data, response) -> Data in
guard let http = response as? HTTPURLResponse,
http.statusCode == 200 else {
throw ApiError.responseError
}
return data
}
.decode(type: PokemonList.self, decoder: JSONDecoder())
.receive(on: RunLoop.main)
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
break
case .failure(let error):
print(error)
}
}, receiveValue: {
promice(.success($0.results))
})
.store(in: &self.cancellables)
}
}
}
struct ContentView: View {
#StateObject var net = NetworkManager()
var body: some View {
List(net.pokemon, id: \.self) { pokemon in
Text(pokemon.name)
}.onAppear {
net.runFetch() //call runFetch instead of fetchPokemon
}
}
}
Since you didn't include the code for PokemonList I made an assumption about it's content:
struct PokemonList: Codable {
var results: [Pokemon]
}
If the type is different, you'll have to change what happens in receiveValue in runFetch.
I've created a sample blank project with single View Controller in main.storyboard and here is implementation below:
import UIKit
import AVFoundation
private enum DownloadErrors: Error {
case invalidRequest
case noResponse
case noTemporaryURL
case noCacheDirectory
case inplayable
case fileNotExists
case system(error: Error)
var localizedDescription: String {
switch self {
case .invalidRequest:
return "invalid request"
case .noResponse:
return "no response"
case .noTemporaryURL:
return "no temporary URL"
case .noCacheDirectory:
return "no cache directory"
case .inplayable:
return "invalid to play"
case .fileNotExists:
return "file not exists"
case let .system(error):
return error.localizedDescription
}
}
}
class ViewController: UIViewController {
// MARK: - View Life Cycle
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.test()
}
// MARK: - Private API
private func test() {
self.download(with: self.request, completion: { result in
switch result {
case let .failure(error):
print("failure: \(error.localizedDescription)")
return
case let .success(url):
self.play(atURL: url)
}
})
}
private let request: URLRequest? = {
var components = URLComponents()
components.scheme = "https"
components.host = "islex.arnastofnun.is"
components.path = "/islex-files/audio/10/1323741.mp3"
guard let url = components.url else {
return nil
}
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("audio/mpeg", forHTTPHeaderField: "Content-Type")
request.setValue(
"attachment; filename=\"1323741.mp3\"",
forHTTPHeaderField: "Content-Disposition"
)
print(request.url?.absoluteString ?? "invalid URL")
return request
}()
private typealias Callback = (Result<URL, DownloadErrors>) -> Void
private func download(with nilableRequest: URLRequest?, completion: #escaping Callback) {
guard let request = nilableRequest else {
completion(.failure(.invalidRequest))
return
}
let task = URLSession.shared.downloadTask(with: request) { (rawTemporaryFileURL, rawResponse, rawError) in
if let error = rawError {
completion(.failure(.system(error: error)))
return
}
guard let httpStatusCode = (rawResponse as? HTTPURLResponse)?.statusCode else {
completion(.failure(.noResponse))
return
}
print("http status code: \(httpStatusCode)")
guard let sourceFileURL = rawTemporaryFileURL else {
completion(.failure(.noTemporaryURL))
return
}
guard let cache = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first else {
completion(.failure(.noCacheDirectory))
return
}
let targetFileURL = cache.appendingPathComponent("audio_10_1323741.mp3")
if !FileManager.default.fileExists(atPath: targetFileURL.path) {
do {
try FileManager.default.moveItem(at: sourceFileURL, to: targetFileURL)
} catch let error {
completion(.failure(.system(error: error)))
}
}
DispatchQueue.main.async {
completion(.success(targetFileURL))
}
}
task.resume()
}
private func play(atURL url: URL) {
do {
guard FileManager.default.fileExists(atPath: url.path) else {
print("play: \(DownloadErrors.fileNotExists)")
return
}
let player = try AVAudioPlayer(contentsOf: url)
player.volume = 1.0
player.prepareToPlay()
player.play()
print("play: finished")
} catch let error {
print("play error: \(error.localizedDescription)")
}
}
}
What did I do wrong? I have a success response and get no error while trying to create an audio player with an url, however my player doesn't play anything. I am trying to download and play a file immediately from the link:
Audio
My log in console of Xcode:
https://islex.arnastofnun.is/islex-files/audio/10/1323741.mp3
http status code: 200
play: finished
Since you are inside a completion block, you most likely need to enclose your call inside a DispatchQueue block to explicitly run it on the main thread. In short, you do this:
DispatchQueue.main.async {
self.play(atURL: url)
}
I have this Networking class that i declared in the Model .
class Networking {
func response (url : String ) {
guard let url = URL(string: url) else {return}
URLSession.shared.dataTask(with: url, completionHandler: urlPathCompletionHandler(data:response:error:)).resume()
}
func urlPathCompletionHandler (data : Data? , response: URLResponse? , error: Error? ) {
guard let data = data else {return }
do {
let jsondecoder = JSONDecoder()
}catch {
print("Error \(error)")
}
}
}
In the controller . I have an array of users i declared and i want the controller to call from the Model Networking class instead of doing the networking inside the controller. This is part of my controller:
var users = [Users]()
var networking : Networking()
#IBOutlet weak var tableview : UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
}
func getFromModel() {
var vm = networking.response()
}
I want a way of calling the networking class and return an array of users that i can set to the users array above and use it to populate the table view . If i wanted to do that inside the controller it would easy but i am not sure how i can return an array of users from the Model Networking class .
You need to modify your Network class like this:
class Networking {
func response<T: Codable>(url: String, completion: ((T) -> Void)?) {
guard let url = URL(string: url) else {return}
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
self.urlPathCompletionHandler(data: data, response: response, error: error, completion: completion)
}).resume()
}
func urlPathCompletionHandler<T: Codable>(data : Data? , response: URLResponse? , error: Error?, completion: ((T) -> Void)?) {
guard let data = data else { return }
do {
let jsondecoder = JSONDecoder()
// Pseudo Code to decode users
completion?(decodedObject)
} catch {
print("Error \(error)")
}
}
}
And call it like this:
func getFromModel() {
networking.response(url: <#T##String#>) { (users: [User]) in
self.users = users
}
}
OK, there are a few thoughts:
Your response method is performing an asynchronous network request, so you need to give it a completion handler parameter. So, I might suggest something like:
class Networking {
enum NetworkingError: Error {
case invalidURL
case failed(Data?, URLResponse?)
}
private let parsingQueue = DispatchQueue(label: Bundle.main.bundleIdentifier! + ".parsing")
// response method to handle network stuff
func responseData(_ string: String, completion: #escaping (Result<Data, Error>) -> Void) {
guard let url = URL(string: string) else {
completion(.failure(NetworkingError.invalidURL))
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
DispatchQueue.main.async {
if let error = error {
completion(.failure(error))
return
}
guard
let responseData = data,
let httpResponse = response as? HTTPURLResponse,
200 ..< 300 ~= httpResponse.statusCode
else {
completion(.failure(NetworkingError.failed(data, response)))
return
}
completion(.success(responseData))
}
}.resume()
}
// response method to handle the JSON parsing
func response<T: Decodable>(of type: T.Type, from string: String, completion: #escaping (Result<T, Error>) -> Void) {
responseData(string) { result in
switch result {
case .failure(let error):
completion(.failure(error))
case .success(let data):
self.parsingQueue.async {
do {
let responseObject = try JSONDecoder().decode(T.self, from: data)
DispatchQueue.main.async {
completion(.success(responseObject))
}
} catch let parseError {
DispatchQueue.main.async {
completion(.failure(parseError))
}
}
}
}
}
}
}
This obviously assumes that you have some Codable types. For example, it’s common for an API to have some common structure in its responses:
struct ResponseObject<T: Decodable>: Decodable {
let code: Int
let message: String?
let data: T?
}
And maybe the User is like so:
struct User: Decodable {
let id: String
let name: String
}
Then getFromModel (perhaps better called getFromRepository or something like that) could parse it with:
networking.response(of: ResponseObject<[User]>.self, from: urlString) { result in
switch result {
case .failure(let error):
print(error)
case .success(let responseObject):
let users = responseObject.data
// do something with users
}
}
For what it’s worth, if you didn’t want to write your own networking code, you could use Alamofire, and then getFromModel would do:
AF.request(urlString).responseDecodable(of: ResponseObject<[User]>.self) { response in
switch response.result {
case .failure(let error):
print(error)
case .success(let responseObject):
let users = responseObject.data
}
}
Now, clearly the model types are likely to be different in your example, but you didn’t share what your JSON looked like, so I had to guess, but hopefully the above illustrates the general idea. Make a generic-based network API and give it a completion handler for its asynchronous responses.