-1

i wrote a 2 classes in my app that need to perform as data classes . one is for the user details and one is for the products. both of the classes is the same code with different names and variables. the products class works ok but the user class don't make the sharedInstance for me. the Json get the data ok and i can print it.

here is my code:

import UIKit
import Alamofire
import SwiftyJSON

class userDetailsDataClass {
    let defaults = NSUserDefaults.standardUserDefaults()
    var user: [SwiftyJSON.JSON] = []



    init() {
        let baseUrlString =  "http://example.com/ios/login.php?"
        let parameters = [String:String]()

        let urlSignup = baseUrlString + "id=" + defaults.stringForKey("userID")! + "&macnumber=" + defaults.stringForKey("currentUUID")!

        //Encode url to solve spaces issues
        let urlwithPercentEscapes = urlSignup.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())!
        print(urlwithPercentEscapes)
        Alamofire.request(.GET, urlwithPercentEscapes, parameters: parameters).responseJSON { response in
            if response.result.isSuccess {
                let json = JSON(response.result.value!)
                let data = json.arrayValue
                print(json)


                if json["error"] == "wrongmac" {
                    print("wrong mac")

                } else {

                    let macFromDb = json["macnumber"]
                    self.defaults.setValue(String(macFromDb), forKey: "macFromDb")

                  userDetailsDataClass.sharedInstance.user = data


                  print(String(userDetailsDataClass.sharedInstance.user.count)+"user count from alamo ")


                }

            }

            let nc = NSNotificationCenter.defaultCenter()
           nc.postNotificationName("userDataReadyForSplash", object: nil)


        }


    }



    //Create one class for shared Instance
    struct Static {
        static var onceToken : dispatch_once_t = 0
        static var instance : userDetailsDataClass? = nil
    }

    class var sharedInstance : userDetailsDataClass {
        dispatch_once(&Static.onceToken){
            Static.instance = userDetailsDataClass()
        }
        return Static.instance!
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Nir Tzin
  • 45
  • 1
  • 6
  • 1
    Avoid using singletons if you can. If you can't, make them real singletons, like this: http://stackoverflow.com/a/36012158/2227743 – Eric Aya May 25 '16 at 08:31

1 Answers1

0

The Singleton should be defined directly in the class and not as a subclass (and please put an Uppercase for the first character in the class Name):

class UserDetailsDataClass {
    static let sharedInstance = UserDetailsDataClass()

    let defaults = NSUserDefaults.standardUserDefaults()
    var user: [SwiftyJSON.JSON] = []


    init() {
        let baseUrlString =  "http://example.com/ios/login.php?"
        let parameters = [String:String]()

        let urlSignup = baseUrlString + "id=" + defaults.stringForKey("userID")! + "&macnumber=" + defaults.stringForKey("currentUUID")!

        //Encode url to solve spaces issues
        let urlwithPercentEscapes = urlSignup.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())!
        print(urlwithPercentEscapes)
        Alamofire.request(.GET, urlwithPercentEscapes, parameters: parameters).responseJSON { response in
            if response.result.isSuccess {
                let json = JSON(response.result.value!)
                let data = json.arrayValue
                print(json)


                if json["error"] == "wrongmac" {
                    print("wrong mac")

                } else {

                    let macFromDb = json["macnumber"]
                    self.defaults.setValue(String(macFromDb), forKey: "macFromDb")

                    UserDetailsDataClass.sharedInstance.user = data

                    // ADDITION: Try to print the whole SwiftyJSON array and see the result
                    print(UserDetailsDataClass.sharedInstance.user)

                    print(String(userDetailsDataClass.sharedInstance.user.count)+"user count from alamo ")
                }
            }

            let nc = NSNotificationCenter.defaultCenter()
            nc.postNotificationName("userDataReadyForSplash", object: nil)
        }
    }
}
Artheyn
  • 1,042
  • 10
  • 7
  • i got a little confused with that. can you please edit my code and post here so i will see the hwole code and understand? – Nir Tzin May 25 '16 at 08:00
  • I've edited my answer. Please try this and see what's printed when you do `print(UserDetailsDataClass.sharedInstance.user)` after you set it. – Artheyn May 25 '16 at 11:56
  • hi, tnx for the diting :). i tried your code and i get exaxtlly the same result.its do not create it right. in i try userDetailsDataClass.sharedInstance.user.count i get 0 – Nir Tzin May 28 '16 at 13:34
  • i made a try, i tried to enter the data into the user: self.user = data and when i print i get empty [ ] .what is wrong here? – Nir Tzin May 28 '16 at 13:43
  • i think i found the problem. if i print the json i see the user details. if i try to print json.arrayValue i get empty [ ]. any idears ? – Nir Tzin May 28 '16 at 13:49
  • found the solution. some times if the json have only one results so he isnt an array... the arrayValue works only on arrays and if the jason in now proper array its gives []. – Nir Tzin May 29 '16 at 13:18
  • Ah right! Sorry for my late answer. So it was just a parsing issue. Good you find it! :) – Artheyn Jun 02 '16 at 08:04