swift alamofire return value is empty - swift

Hi i have the following method:
func getAlamoPlayers() ->[Player]{
//Get TeamID
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var TeamId:String = prefs.stringForKey("TEAMID")!
//create parameters for POST
let parameters =
["IdTeam": TeamId]
var result: NSArray?
//Request
Alamofire.request(.POST, "XXXXXX.php", parameters: parameters)
.responseJSON { (request, response, json, error) -> Void in
result = (json as NSArray)
// Make models from Json data
for (var i = 0; i < result?.count; i++) {
let dic: NSDictionary = result![i] as NSDictionary
//Create a team object
var p:Player = Player()
//Assign the values of each key value pair to the team object
p.PlayerID = dic["IdPlayer"] as String
p.PlayerName = dic["name"] as String
p.PlayerFkToTeam = dic["teams_IdTeam"] as String
//Add the team to the player array
self.players.append(p)
}
}
return self.players
}
So when i call this method in another class the players array is empty! How can I handle the asynchronous request of alamofire? I think the method returns the player object before the request is finished, or am I wrong?
Thanks in advance!

Here is a question that asks basically the same thing you are.
AlamoFire GET api request not working as expected
So basically what is happening is that your post request is being called in a background queue. So think of it as calling your post then continuing on to the next line. So since it is in a background thread it doesn't set the variable till after your function returns.
You could use a completion handler as explained in detail in the link I provided. Another solution would be to use NSNotificationCenter. Set up an observer and then post a notification inside your POST request.
So for example:
First declare your notification name at the top of the class where you will have your post response function as so. So that other classes can access it
let YOUR_NOTIFICATION_NAME = "NOTIFICATION NAME"
class YOUR_CLASS{
then inside the class write the code you want to execute once the POST is done.
func YOUR_FUNCTION{
...
}
Then before you execute your POST request you want to add an observer.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "YOUR_FUNCTION", name: YOUR_NOTIFICATION_NAME, object: nil)
Then post your notification inside your POST request.
Alamofire.request(.POST, "XXXXXX.php", parameters: parameters)
.responseJSON { (request, response, json, error) -> Void in
...<your code>...
self.players.append(p)
NSNotificationCenter.defaultCenter().postNotificationName(YOUR_NOTIFICATION_NAME, object: self)
}

so i've build it in the following way:
Modell Class with all requests:
let finishedPlayers = "finishedPlayers"
class StrafenkatalogModel: NSObject {
.
.
func getAlamoPlayers()-> [Player] {
//Get TeamID
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var TeamId:String = prefs.stringForKey("TEAMID")!
//create parameters for POST
let parameters =
["IdTeam": TeamId]
var result: NSArray?
//Observer
NSNotificationCenter.defaultCenter().addObserver(self, selector: "returnPlayers", name: finishedPlayers, object: nil)
//Request
Alamofire.request(.POST, "http://smodeonline.com/XXXXXXX.php", parameters: parameters)
.responseJSON { (request, response, json, error) -> Void in
result = (json as NSArray)
// Make models from Json data
for (var i = 0; i < result?.count; i++) {
let dic: NSDictionary = result![i] as NSDictionary
//Create a team object
var p:Player = Player()
//Assign the values of each key value pair to the team object
p.PlayerID = dic["IdPlayer"] as String
p.PlayerName = dic["name"] as String
p.PlayerFkToTeam = dic["teams_IdTeam"] as String
//Add the team to the teams array
self.players.append(p)
}
}
return players
}
func returnPlayers() ->[Player]{
return self.players
}
Then i want to call it in the TableViewController class (Class2):
class AddPlayersTableViewController: UITableViewController {
let model:StrafenkatalogModel = StrafenkatalogModel()
var players:[Player] = [Player]()
override func viewDidLoad() {
super.viewDidLoad()
// Get Player objects from the model
NSNotificationCenter.defaultCenter().postNotificationName("finishedPlayers", object: self)
self.players = self.model.returnPlayers()
.
.
}
But the players object is empty. Does you know why? Did i something wrong?

Related

Swift Pusher example doing nothing

I am using the starter code Pusher provides, when I put it into a basic swift project and I send it a message nothing happens. I have the cocoa pod package installed as well.
The statement "data received" should print.
There are also no errors.
Are you initialising the Pusher object as a var? You need to maintain a strong reference to the object otherwise it can become deallocated.
As an example it should be something like:
class ViewController: UIViewController {
var pusher: Pusher!
override func viewDidLoad() {
super.viewDidLoad()
let options = PusherClientOptions(
host: .cluster("mycluster")
)
pusher = Pusher(
key: "app_key",
options: options
)
// subscribe to channel and bind to event
let channel = pusher.subscribe("my-channel")
let _ = channel.bind(eventName: "my-event", callback: { (data: Any?) -> Void in
if let data = data as? [String : AnyObject] {
if let message = data["message"] as? String {
print(message)
}
}
})
pusher.connect()
}
}

Proper way to call asynchronous function in swift singleton

I want to build an analytics class for my application, and i am using singleton.
If I run this, the tagEvent function immediately runs rather than first running the openSession(), so sessionId returns nil.
How can I create a class like this with proper initialisation and use it application wide like singleton instances.
Analytics.swift
final class Analytics {
public static let instance = Analytics()
private var baseUrl = "http://localhost"
public var deviceId: String?
private init(){
self.deviceId = SomeFunctionGetsDeviceID()
}
func openSession(){
// make an API call to create a session and save sessionId to UserDefaults
if let url = URL(string: self.baseUrl + "/session"){
let params:[String:Any] = ["deviceId": "\(self.deviceId!)"]
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField:"Content-Type")
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: [])
AnalyticsSessionManager.sharedManager.request(request as URLRequestConvertible).validate().responseObject(completionHandler: { (response: DataResponse<SessionOpenResponse>) in
if response.result.value != nil {
UserDefaults.standard.set(response.result.value?.sessionId, forKey: "sessionId")
}
})
}
}
func closeSession(){
// make an API call to close a session and delete sessionId from UserDefaults
...
}
func tagEvent(eventName: String, attributes: [String : String]? = nil) {
if let url = URL(string: self.baseUrl + "/event"),
let sessionId = UserDefaults.standard.string(forKey: "sessionId"){
...
// make an API call to create an event with that sessionId
}
}
}
AppDelegate.swift
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Analytics.instance.openSession()
Analytics.instance.tagEvent(eventName: "App Launch", attributes:
["userID":"1234"])
}
My best guess is the openSession function is doing work asynchronously and the tagEvent call comes in BEFORE the asynchronous code has completed. There are a couple of ways around this:
1) Add synchronization so the tagEvent code will wait for the openSession call to complete (if in progress). If not in progress, perhaps it should automatically call openSession, wait for completion, then execute the code in that function
2) Add a completion handler from openSession and inside that enclosure you can call tagEvent such as:
func openSession(completionHandler: #escapaing (Bool) -> ()){
// make an API call to create a session and save sessionId to UserDefaults
...
UserDefaults.standard.set(someSessionID, forKey: "sessionId")
// when done with async work
completionHandler(true)
}
Then in your app delegate:
Analytics.instance.openSession() { (success)
Analytics.instance.tagEvent(eventName: "App Launch", attributes:["userID":"1234"])
}
3) * This is the way I would fix it * I would not make a call to openSession to be required outside of the class. I would add a flag to the Analytics class:
private var initialized = false
In the openSession function, set this after everything is done
initialized = true
In the tagEvent function:
func tagEvent(eventName: String, attributes: [String : String]? = nil) {
// Check for initialization
if (!initialized) {
openSession() { (success) in
// perform your tagEvent code
})
} else {
if let url = URL(string: self.baseUrl + "/event"),
let sessionId = UserDefaults.standard.string(forKey: "sessionId"){
...
// make an API call to create an event with that sessionId
}
}
}
You can implement an "internal" class to provide a static reference to your Analytics class, as follows (note: remove final keyword):
class Analytics {
// properties ...
class var sharedInstance: Analytics {
struct Static {
static let instance: Analytics = Analytics()
}
return Static.instance
}
// other methods (init(), openSession(), closeSession(), tagEvent())
}
Next call methods from your Analytics class in any other class, as follows:
Analytics.sharedInstance.openSession()
Analytics.sharedInstance.closeSession()
Analytics.sharedInstance.tagEvent( ... )

swift 2 UITableView Refresh after Almofire

I know almofire works as a thread in the background so I put in my main class
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: "taskdataReadyFunc", name: "taskdataReady", object: nil)
and in my dataClass after the almofire finish:
init() {
Alamofire.request(.GET, urlString, parameters: parameters).responseJSON { response in
if response.result.isSuccess {
let json = JSON(response.result.value!)
let data = json.arrayValue
self.tasks = data
print(self.tasks)
}
// print(self.tasks)
print(String(self.tasks.count)+"before nc")
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName("taskdataReady", object: nil)
}
that leads to thet function:
func taskdataReadyFunc (){
tableView.reloadData()
print("reload mision table" + String(taskDataClass.sharedInstance.tasks.count))
}
This worked fine when I start the app for the first time.
my problem is that I made a new task that adds a new task to the database and then tries to run the init of the dataClass again. at that stage, i can see the new task coming from the DB but it not make a table reload data.(if I close and open the app I see it)
how can I refresh my table view or maybe to close and open the controller from the start ?
I'm not sure what you're trying to do with self.tasks = data, but normal Alamofire usage combined with NSNotification would look like this:
request(.GET, urlString, parameters: parameters).responseJSON { response in
guard let json = response.result.value else { return } // handle error
let notification = NSNotification(name: "taskDataReady", object: nil, userInfo: ["taskData" : json])
NSNotificationCenter.defaultCenter().postNotification(notification)
}
Then you would unwrap the JSON value from the notification. I'd actually recommend decoding the JSON into an actual type from within the Alamofire completion handler and encapsulating that within an NSNotification, so you don't have to do additional work in the view controller.
the sharedInstance is create only one time when you first call it.
its called singleTon.
that means that if the init() function fill the variable in the class the sharedInstance will not be update.
so, in the init class, even in the first run update the sharedInstance and not the variable.
example:
//self.tasks = data
taskDataClass.sharedInstance.tasks = data

Code maintaining at delegates and callback pattern

First of all, I am just a beginner who is currently developing an app with the Swift language, so please don't mind my question too much because I really need to know and I am having trouble with maintaining the code that I constructed.
It's about the async delegate pattern.
Here is my API class. Assume that there are many API classes like that which makes async calls.
protocol InitiateAPIProtocol{
func didSuccessInitiate(results:JSON)
func didFailInitiate(err:NSError)
}
class InitiateAPI{
var delegate : InitiateAPIProtocol
init(delegate: InitiateAPIProtocol){
self.delegate=delegate
}
func post(wsdlURL:String,action:String,soapMessage : String){
let request = NSMutableURLRequest(URL: NSURL(string: wsdlURL)!)
let msgLength = String(soapMessage.characters.count)
let data = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
request.HTTPMethod = "POST"
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue(msgLength, forHTTPHeaderField: "Content-Length")
request.addValue(action, forHTTPHeaderField: "SOAPAction")
request.HTTPBody = data
let task = session.dataTaskWithRequest(request) {
data, response, error in
if error != nil {
self.delegate.didFailInitiate(error!)
return
}
let jsonData = JSON(data: data)
self.delegate.didSuccessInitiate(jsonData)
}
task.resume()
}
func doInitiate(token : String){
let soapMessage = “”
// WSDL_URL is the main wsdl url i will request.
action = “”
post(WSDL_URL, action: action, soapMessage: soapMessage)
}
}
Here is my ViewController:
class ViewController : UIViewController,InitiateAPIProtocol{
var initiateAPI : InitiateAPI!
var token : String = “sWAFF1”
override func viewWillAppear(animated: Bool) {
// Async call start
initiateAPI = InitiateAPI(delegate:self)
initiateAPI.doInitiate(token)
}
// Here comes call back
func didSuccessInitiate(results: JSON) {
//handle results
}
func didFailInitiate(err: NSError) {
//handle errors
}
}
My problem is I said that there are many API classes like that, so if one view controller handles 4 API classes, I have to handle many protocol delegates methods as I extend the view controller. There will be many delegates method below of view controller. If other view controllers call the same API and have to handle the same delegates, I have a problem maintaining the code because every time I change some delegate parameters, I have to fix the code at all view controllers which use those API classes.
Is there any other good way to handle async call?
If my question seems a little complex, please leave a comment, I will reply and explain it clearly.
Delegates (OOP) and "completion handlers" (function like programming) just don't fit well together.
In order to increase comprehension and to make the code more concise, an alternative approach is required. One of this approach has been already proposed by #PEEJWEEJ using solely completion handlers.
Another approach is using "Futures or Promises". These greatly extend the idea of completion handlers and make your asynchronous code look more like synchronous.
Futures work basically as follows. Suppose, you have an API function that fetches users from a remote web service. This call is asynchronous.
// Given a user ID, fetch a user:
func fetchUser(id: Int) -> Future<User> {
let promise = Promise<User>()
// a) invoke the asynchronous operation.
// b) when it finished, complete the promise accordingly:
doFetchAsync(id, completion: {(user, error) in
if error == nil {
promise.fulfill(user!)
} else {
promise.reject(error!)
}
})
return.promise.future
}
First, the important fact here is, that there is no completion handler. Instead, the asynchronous function returns you a future. A future represents the eventual result of the underlying operation. When the function fetchUser returns, the result is not yet computed, and the future is in a "pending" state. That is, you cannot obtain the result immediately from the future. So, we have to wait?? - well not really, this will be accomplished similar to an async function with a completion handler, i.e. registering a "continuation":
In order to obtain the result, you register a completion handler:
fetchUser(userId).map { user in
print("User: \(user)")
}.onFailure { error in
print("Error: \(error)")
}
It also handles errors, if they occur.
The function map is the one that registered the continuation. It is also a "combinator", that is it returns another future which you can combine with other functions and compose more complex operations.
When the future gets finally completed, the code continues with the closure registered with the future.
If you have two dependent operations, say OP1 generates a result which should be used in OP2 as input, and the combined result should be returned (as a future), you can accomplish this in a comprehensive and concise manner:
let imageFuture = fetchUser(userId).flatMap { user in
return user.fetchProfileImage()
}
imageFuture.onSuccess { image in
// Update table view on main thread:
...
}
This was just a very short intro into futures. They can do much more for you.
If you want to see futures in action, you may start the Xcode playgrounds "A Motivating Example" in the third party library FutureLib (I'm the author). You should also examine other Future/Promise libraries, for example BrightFutures. Both libraries implement Scala-like futures in Swift.
Have you looked into NSNotificationCenter?
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/
You'll be able to post events from your api class, then each view controller would subscribe to the events and be notified accordingly
Does that make sense? There are lots of good examples of this pattern:
https://stackoverflow.com/a/24049111/2678994
https://stackoverflow.com/a/28269217/2678994
I've updated your code below:
class InitiateAPI{
//
// var delegate : InitiateAPIProtocol
// init(delegate: InitiateAPIProtocol){
// self.delegate=delegate
// }
func post(wsdlURL:String,action:String,soapMessage : String){
let request = NSMutableURLRequest(URL: NSURL(string: wsdlURL)!)
let msgLength = String(soapMessage.characters.count)
let data = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
request.HTTPMethod = "POST"
request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.addValue(msgLength, forHTTPHeaderField: "Content-Length")
request.addValue(action, forHTTPHeaderField: "SOAPAction")
request.HTTPBody = data
let task = session.dataTaskWithRequest(request) {
data, response, error in
if error != nil {
// self.delegate.didFailInitiate(error!)
/* Post notification with error */
NSNotificationCenter.defaultCenter().postNotificationName("onHttpError", object: error)
return
}
let jsonData = JSON(data: data)
// self.delegate.didSuccessInitiate(jsonData)
/* Post notification with json body */
NSNotificationCenter.defaultCenter().postNotificationName("onHttpSuccess", object: jsonData)
}
task.resume()
}
func doInitiate(token : String){
let soapMessage = “”
// WSDL_URL is the main wsdl url i will request.
action = “”
post(WSDL_URL, action: action, soapMessage: soapMessage)
}
}
Your view controller class:
class ViewController : UIViewController { //,InitiateAPIProtocol{
var initiateAPI : InitiateAPI!
var token : String = “sWAFF1”
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.didSuccessInitiate(_:)), name: "onHttpSuccess", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.didFailInitiate(_:)), name: "onHttpError", object: nil)
}
override func viewWillAppear(animated: Bool) {
// Async call start
initiateAPI = InitiateAPI(delegate:self)
initiateAPI.doInitiate(token)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
/* Remove listeners when view controller disappears */
NSNotificationCenter.defaultCenter().removeObserver(self, name: "onHttpSuccess", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: "onHttpError", object: nil)
}
// Here comes call back
func didSuccessInitiate(notification : NSNotification) { //results: JSON) {
if let payload = notification.object as? JSON {
//handle results
}
}
func didFailInitiate(notification : NSNotification) { //err: NSError) {
if let payload = notification.object as? NSError {
//handle errors
}
}
}
Instead of using a delegate, you could (should?) use closers/functions:
func post(/*any other variables*/ successCompletion: (JSON) -> (), errorCompletion: (NSError) ->()){
/* do whatever you need to*/
/*if succeeds*/
successCompletion("")
/*if fails*/
errorCompletion(error)
}
// example using closures
post({ (data) in
/* handle Success*/
}) { (error) in
/* handle error */
}
// example using functions
post(handleData, errorCompletion: handleError)
func handleData(data: JSON) {
}
func handleError(error: NSError) {
}
This would also give you the option to handle all the errors with one function.
Also, it's ideal to parse your JSON into their desired objects before returning them. This keeps your ViewControllers clean and makes it clear where the parsing will occur.

SwiftyJSON how to correctly access variables?

I try to figure out SwiftyJSON but I'm facing a problem
The code shown below works fine
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://api.whitehouse.gov/v1/petitions.json")
var request = NSURLRequest(URL: url!)
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
if data != nil {
let hoge = JSON(data: data!)
let count = hoge["results"][0]["body"]
println(count)
}
}}
but when i try to add a method which accesses the hoge it returns nothing
code looks like this
func res() {
dump(hoge)
}
I tried to declare let hoge and let count in the header of ViewController, but it always gives errors.
How to do it correctly, so i can access array thorough all the code ?
Thanks in advance
If you declare a variable inside a function, like you do here in viewDidLoad, this variable is only available in the same scope, meaning that variable doesn't exist outside viewDidLoad. Actually it is even deallocated (destroyed) when the function execution finishes.
The solution is to create var hoge: JSON? at the root of your class, outside any function, then only assign the JSON value to this variable when it is available:
class ViewController: UIViewController {
var hoge: JSON?
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://api.whitehouse.gov/v1/petitions.json")
var request = NSURLRequest(URL: url!)
var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
if data != nil {
hoge = JSON(data: data!)
let count = hoge!["results"][0]["body"]
println(count)
}
}}
That way you can also create other methods that can access hoge outside of viewDidLoad.