I have an issue understanding the process in consuming REST api services with SWIFT, seems like i'm missing something simple, but yet important here.
this is the singleton DataManager class, I'm using to consume API with loadNews() method, as you can see it's simple, request method, getter and initializer that will load the data.
for loadNews() I use Alamofire to handle request, and SwiftyJSON to parse the response.
class DataManager{
static let shared = DataManager()
private var data:JSON = JSON()
private init(){
print("testprint1 \(self.data.count)")
loadNews() { response in
self.data = response
print("initprint \(self.data.count)")
print(self.data["response"]["results"].count)
print(self.data["response"]["results"][0]["id"].stringValue)
}
print("testprint2 \(self.data.count)")
}
func getNews() -> JSON {
return data
}
func loadNews(completion: #escaping (JSON) -> ()){
Alamofire.request("...")
.responseJSON{ response in
guard response.result.isSuccess,
let value = response.result.value else {
print("Error: \(String(describing: response.result.error))")
completion([])
return
}
let json = JSON(value)
completion(json)
}
}
}
issue that i'm facing is when i try to call the DataManager() instance in my ViewController, I'm not able to read data in the controller for some reason, here is the controller code (relevant one):
class SecondViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
let data1 = DataManager.shared.getNews()
print("qa \(data1.count)")
}
...
}
now what bothers me is - logic behind this should be simple, let data1 = DataManager.shared.getNews() - if i'm not wrong will (should) execute the following flow:
init()->loadNews()->getNews()
initialize method will call loadNews, loadNews will fetch data from API, fill the data array, and getNews is supposed to return the filled data array, but that flow doesn't seem correct then
console output
console output text
testprint1 0
testprint2 0
qa 0
initprint 1
50
commentisfree/2019/dec/07/lost-my-faith-in-tech-evangelism-john-naughton
so it seems like both prints within init() get executed before loadNews() method that is between them, as well as "qa0" print that is printing the size of the array in the ViewController.
now my question is, does anyone see a mistake here, is this happening because of long network query, or am I just missing something, because it seems to me that data is properly loaded and parsed, which is seen in last 2 lines of output, but i can't get it where i need it, like it dissapears. is my logic here wrong? if someone could help I would really appreciate it.
The Alamofire process works asynchronously, but you don't consider it, that's the mistake.
Change the code to
class DataManager{
static let shared = DataManager()
func loadNews(completion: #escaping (JSON) -> ()){
Alamofire.request("...")
.responseJSON{ response in
guard response.result.isSuccess,
let value = response.result.value else {
print("Error:", response.result.error)
completion([])
return
}
let json = JSON(value)
completion(json)
}
}
}
class SecondViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
DataManager.shared.loadNews() { response in
print("initprint \(response.count)")
print(response["response"]["results"].count)
print(response["response"]["results"][0]["id"].stringValue)
}
}
...
}
You have to get the data from the completion handler in SecondViewController
Related
I'm looking to run a Cloud-Code function from a Swift application and receive an object as a response. The response object from Parse is a standard JSON object as defined below and is not an object stored is Parse. Essentially, I'm looking to end up with an custom object defining the results of a cloud function's execution, not an object stored in the database.
I'm struggling with decoding the CloudCode response on the Swift side of things to a custom object following the Decodable protocol.
Sample Cloud Code
Parse.Cloud.define("MyCloudFunc", function(request, response) {
var results = {
"someBooleanProperty": true,
"someIntProperty": 1,
};
response.success(results);
}
Sample Swift Code
PFCloud.callFunction(inBackground: "MyCloudFunc", withParameters: []) { (result, error) in
// Printing `result` at this point shows what appears to be a JSON object.
guard let data = result as? Data else { return }
// Whatever type `result` actually is cannot be cast as Data, so we never make it past here.
guard let response = try? JSONDecoder().decode(MyDecodableStruct, from: data) else { return }
// DO SOMETHING WITH THE RESULT
}
Decodable Struct
struct MyDecodableStruct: Decodable {
var someBooleanProperty:Bool
var someIntProperty: Int
}
Question
How can I take that response from the Parse Cloud Code and end up with a decoded object of type MyDecodableStruct?
UPDATE
As suggested in the comments/answers, Parse is returning a Dictionary. I have been able to get everything working with the below; however, I feel there is a better way than double-conversion.
PFCloud.callFunction(inBackground: "MyCloudFunc", withParameters: []) { (result, error) in
guard let jsonString = result as? String else { return }
guard let data = jsonString.data(using: String.Encoding.utf8) else { return }
guard let response = try? JSONDecoder().decode(MyDecodableStruct.self, from: data) else { return }
// DO SOMETHING WITH RESULT.
}
Am I overlooking a way to convert from the Dictionary directly Data without doing the JSON conversion in-between?
Part of PFCloud's job is to create generic collection types from the cloud function response. Since the cloud function is answering a JS object, PFCloud should -- without the app noticing -- transmit JSON and parse it before invoking the callFunction callback.
So the posted cloud code result will the be a dictionary. Check to see that with...
if result is Dictionary<AnyHashable,Any> {
print("result is a Dictionary")
}
To convert that to the OP struct, add a from-dictionary initializer to it...
struct MyDecodableStruct: Decodable {
var someBooleanProperty:Bool
var someIntProperty: Int
init(dictionary: [AnyHashable,Any]) {
self.someBooleanProperty = dictionary["someBooleanProperty"] as? Bool ?? false
self.someIntProperty = dictionary["someIntProperty"] as? Int ?? 0
}
}
I'm a beginner at Swift so let me know if this doesn't quite make sense, but i have a JSON file that i can access in swift and parse into an array, from there i can get a string from the array and store it in a var. I want to be able to access this variable globally but i'm not sure how to do it.
With the help of another user "rmaddy". I have this code:
struct Games: Decodable {
let videoLink: String
}
class BroadService {
static let sharedInstance = BroadService()
func fetchBroadcasts(completion: #escaping ([Games]?) -> ()) {
let jsonUrlString = "LINK IS HERE."
guard let url = URL(string: jsonUrlString) else {
completion(nil)
return
}
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {
completion(nil)
return
}
do {
let games = try JSONDecoder().decode([Games].self, from: data)
completion(games)
} catch let jsonErr {
print("Error deserializing json:", jsonErr)
completion(nil)
}
}.resume()
}
}
I can then access it in another class from here:
BroadService.sharedInstance.fetchBroadcasts { (games) in
if let games = games {
let game = games[indexPath]
let videoLink = game.videoLink
}
I want to be able to access the contents of "videoLink" globally, without having to use "BroadService.sharedInstance.fetchBroadcasts { (games) in" how would i go about doing this
You shouldn't use global variables, I don't think that's recommended in any language.
Now here you have what looks like a Singleton class (BroadService), that's good because it's a nice solution for what you're looking for.
Next all you need to do is add a property to that class. Let's say videoLink is a string, you can add a string property to BroadService, for example storedVideoLink as an optional String, and the next time you need to obtain that value after you have already fetched it, you can access it like so: BroadService.sharedInstance.storedVideoLink.
One more thing, to have BroadService work properly as a singleton, you should make its init private.
To sum up, here's what I'm suggesting:
class BroadService {
static let sharedInstance = BroadService()
var storedVideoLink: String?
private init() {} // to ensure only this class can init itself
func fetchBroadcasts(completion: #escaping ([Games]?) -> ()) {
// your code here
}
}
// somewhere else in your code:
BroadService.sharedInstance.fetchBroadcasts { (games) in
if let games = games {
let game = games[indexPath]
let videoLink = game.videoLink
BroadService.sharedInstance.storedVideoLink = videoLink
}
}
// now you can access it from anywhere as
// BroadService.sharedInstance.storedVideoLink
This way it all stays cohesive in the same class. You can even add a getter method for storedVideoLink so you don't have to access it directly, and in this method you could state that if the string is nil then you fetch the data, store the link to the string, and then return the string.
You could create a file with a struct called something like Global and create a static var and set that inside your completion block once you have fetched the games.
Here is an example.
struct Global {
static var games:[Any]? = nil
static func setGames(games:[Any]) {
Global.games = games
}
}
Then you fetch the data once upon load of the app or somewhere before you use the Global and set that property:
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else {
completion(nil)
return
}
do {
let games = try JSONDecoder().decode([Games].self, from: data)
Global.setGames(games: games)
completion(games)
} catch let jsonErr {
print("Error deserializing json:", jsonErr)
completion(nil)
}
}.resume()
Please note that this will make the Global.games accessible from everywhere but it will also not be a constant so you should be careful not to override it.
This way Global.games will be accessible from anywhere.
How to return what you got?Excuse me, novice, I understand only.enter image description here
enter image description here
Alamofire.request is an asynchronous task, so any code written after this is most likely going to be executed before the task is complete. There are a few ways of doing what you want, but since you haven't provided much information, I have just moved the JSON inside the closure. So you should get something to print out.
Alamofire.request("https://...").responseJSON { (response) in
// Inside this closure is where you receive your JSON
if let value = response.value {
let json = JSON(value)
let title = json["posts", 3, "title"].stringValue
print("Title:", title)
}
}
// Any code after this request will most likely be executed before
// the request has completed because it is done asynchronously.
This is another way that might work better for you.
I understand that you are a beginner and these kinds of operations can be quite complex. You need to understand the order at which code get executed, and how variables work. You are getting that error because swiftyJsonVar is declared in a block that is not accessible to code in the viewDidLoad. I suggest you learn about multi-threading and other asynchronous tasks and probably learn how to declare and use variables properly.
override func viewDidLoad() {
super.viewDidLoad()
load { (json) in
if let json = json {
let title = json["posts", 3, "title"].stringValue
print("Title:", title)
}
}
}
func load(completion: #escaping (JSON?) -> Void){
Alamofire.request("https://httpbin.org/get").responseJSON { (response) in //https://...
var json: JSON?
if let value = response.value {
json = JSON(value)
}
completion(json)
}
}
here is my issue, I would like to create a function with this prototype :
func doPostRequest(......)->JSON()
And I write it like that :
func downloadData(completed:#escaping()->()){
Alamofire.request(url).responseJSON(completionHandler: {
response in
let result = response.result
if let dict = ... {
self._temp = String(format: "%.0f °C", temp - 273.15)
...
}
completed()
})
}
I'd like to return an Any object or dictionary, something with my JSON in... but each time I try to implement return I have a nil object ! Maybe a scope problem how can I implement this function to have
var myJson:NSDictionary
myJson=downloadData(......) ???
Thanks for your help
Since the method in the body works asynchronously you have to declare your request method with an completion handler for example
func doPostRequest(completion: #escaping ([String:Any])->())
On return it passes a Swift dictionary.
The method can be used with this code:
var myJson = [String:Any]()
...
doPostRequest() { json in
self.myJson = json
// do something with the returned data
}
first you need to create a ObjectMapper to map your objects and use AlamofireObjectMapper to get
try this code
request(url, method: .post, parameters:params).validate().responseObject{(response:
DataResponse<objectMapperclass>)in
switch response.result{
case.success(let data):
let objects = data
case.faliure(_):
}
}
I am trying to get learn how to use AlamoFire and I am having trouble.
My method so far is as follows:
func siteInfo()->String?{
var info:NSDictionary!
var str:String!
Alamofire.request(.GET, MY_API_END_POINT).responseJSON {(request, response, JSON, error) in
info = JSON as NSDictionary
str = info["access_key"] as String
//return str
}
return str
}
This returns nil which is a problem. From what I have read here, this is because the request can take a while so the closure doesn't execute till after the return. The suggested solution of moving the return into the closure does not work for me and the compiler just yells (adding ->String after (request,response,JSON,error) which gives "'String' is not a subtype of void"). Same goes for the other solution provided.
Any ideas? Even some source code that is not related to this problem, that uses AlamoFire, would be helpful.
Thanks!
One way to handle this is to pass a closure (I usually call it a completionHandler) to your siteInfo function and call that inside Alamofire.request's closure:
func siteInfo(completionHandler: (String?, NSError?) -> ()) -> () {
Alamofire.request(.GET, MY_API_END_POINT).responseJSON {
(request, response, JSON, error) in
let info = JSON as? NSDictionary // info will be nil if it's not an NSDictionary
let str = info?["access_key"] as? String // str will be nil if info is nil or the value for "access_key" is not a String
completionHandler(str, error)
}
}
Then call it like this (don't forget error handling):
siteInfo { (str, error) in
if str != nil {
// Use str value
} else {
// Handle error / nil value
}
}
In the comments you asked:
So how would you save the info you collect from the get request if you
can only do stuff inside the closure and not effect objects outside of
the closure? Also, how to keep track to know when the request has
finished?
You can save the result of the get request to an instance variable in your class from inside the closure; there's nothing about the closure stopping you from doing that. What you do from there really depends on, well, what you want to do with that data.
How about an example?
Since it looks like you're getting an access key form that get request, maybe you need that for future requests made in other functions.
In that case, you can do something like this:
Note: Asynchronous programming is a huge topic; way too much to cover here. This is just one example of how you might handle the data you get back from your asynchronous request.
public class Site {
private var _accessKey: String?
private func getAccessKey(completionHandler: (String?, NSError?) -> ()) -> () {
// If we already have an access key, call the completion handler with it immediately
if let accessKey = self._accessKey {
completionHandler(accessKey, nil)
} else { // Otherwise request one
Alamofire.request(.GET, MY_API_END_POINT).responseJSON {
(request, response, JSON, error) in
let info = JSON as? NSDictionary // info will be nil if it's not an NSDictionary
let accessKey = info?["access_key"] as? String // accessKey will be nil if info is nil or the value for "access_key" is not a String
self._accessKey = accessKey
completionHandler(accessKey, error)
}
}
}
public func somethingNeedingAccessKey() {
getAccessKey { (accessKey, error) in
if accessKey != nil {
// Use accessKey however you'd like here
println(accessKey)
} else {
// Handle error / nil accessKey here
}
}
}
}
With that setup, calling somethingNeedingAccessKey() the first time will trigger a request to get the access key. Any calls to somethingNeedingAccessKey() after that will use the value already stored in self._accessKey. If you do the rest of somethingNeedingAccessKey's work inside the closure being passed to getAccessKey, you can be sure that your accessKey will always be valid. If you need another function that needs accessKey, just write it the same way somethingNeedingAccessKey is written.
public func somethingElse() {
getAccessKey { (accessKey, error) in
if accessKey != nil {
// Do something else with accessKey
} else {
// Handle nil accessKey / error here
}
}
}