Search code examples
iosswiftalamofire

Use of undeclared type 'JSONDictionary'


I'm working on a project in Swift 2.3 and I'm using the AlamoFire framework and SwiftyJSON as to implement my webserver call methods.

Thus I have written a singleton class as to call these server call functions wherever I want in my project.

Hence for instance once the login button is tapped the login function in this class will execute.

But when I build and run the project and once the login button is tapped the app crashes and I'm getting an issue denoting

Use of Undeclared type 'JSONDictionary'.

The code as bellow and the line I'm getting issue is marked with a comment.

import UIKit
import Alamofire
import SwiftyJSON

struct Singleton {
  static let instance : APIManager = APIManager()
}


public class APIManager: NSObject {

    var appURLs = AppURLs.sharedInstance



  public class var sharedInstance: APIManager {
    return Singleton.instance
  }

  let manager = Manager()

  override init() {

  }
func login(username: String, password: String, completion: (user: User, success: Bool) -> (), failed:(error: NSError) -> ()) -> Request {

    let baseURL = NSURL(string: appURLs.mainBaseURL);
let urlRequest = NSURLRequest(URL: baseURL!.URLByAppendingPathComponent(appURLs.loginURL)!)
 return manager.request(urlRequest)

      .validate()
      .responseJSON { response in
        if let error = response.result.error {
          failed(error: error)
          print(error)
          return;
        }
        print("working up to here")
        let ok = ((response.result.value as! JSONDictionary)["success"] as? Bool)!//This is where I get the issue
        if ok {
        let userJson = JSON((response.result.value as! JSONDictionary)["user"]!)

        let token = ((response.result.value as! JSONDictionary)["token"] as? String)!
        NSUserDefaults.standardUserDefaults().setValue(token, forKey: "TOKEN")
        NSUserDefaults.standardUserDefaults().synchronize()
        //let user = user(json: userJson)
        let user = User()
        user.displayName = userJson ["displayName"].string
        print("displayName is :", user.displayName)

        completion(user: user,success: ok)

}

Solution

  • You should cast what you get from Alamofire to Dictionary or [String: AnyObject].

    Here's a sample code to handle the response value you get:

    // You can add "as? [String:AnyObject]" to the if let statement if you prefer.
    if let jsonResult = response.result.value { // jsonResult is of type [String: AnyObject]
        let jsonObj = JSON(jsonResult)
    
        print(jsonObj)
    }
    

    Then from your jsonObj, you can do something like jsonObj["user"]["token"].string to retrieve the token (don't forget to protect this call with a if let or guard let to make sure the value isn't nil

    EDIT: Here's what your code would look like:

    // you need to change the keys to what the API expect
    return manager.request(.POST, urlRequest, parameters: ["userName": username, "password": password], encoding: .JSON)
    
      .validate()
      .responseJSON { response in
        if let error = response.result.error {
          failed(error: error)
          print(error)
          return;
        }
        print("working up to here")
        if let jsonResult = response.result.value {
            let jsonObj = JSON(jsonResult)
    
            print(jsonObj)
            let ok = jsonObj["success"].bool // or boolValue
    
            if ok != false {
                if let token = jsonObj["user"]["token"].string {
                    NSUserDefaults.standardUserDefaults().setObject(token, forKey: "TOKEN")
                    NSUserDefaults.standardUserDefaults().synchronize()
                }
    
                let user = User()
                user.displayName = jsonObj["user"]["displayName"].string
                print("displayName is :", user.displayName)
    
                completion(user: user,success: ok)
            }
        }