0

Hi there i am currently working on a Api Manager in Swift, what i got so far:

import Foundation
import CoreData
import Alamofire
import SwiftyJSON

class ApiManager {

    var data: NSArray = []

    func getApi() -> NSArray {

        let user:String = "user"
        let password:String = "password"

        Alamofire.request(.GET, "http://localhost/api/")
            .authenticate(user: user, password: password)
            .responseJSON{ (request, response, jsonData, error) in

                if let jsonData1 = jsonData {

                    if let jsonData2 = JSON(jsonData1).dictionaryObject {

                        self.data = jsonData2["data"] as! NSArray

                    }

                }

        }

        return data

    }

}

The JSON Api is correct, but there is something wrong with my swift code, but i am not sure what it is,

When i call this manager:

let response = ApiManager().getApi()
println(response)

I just get empty brackets:

(
)

Anybody could help me with this?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Creative crypter
  • 1,348
  • 6
  • 30
  • 67

2 Answers2

0

This is a faulty design. You should NOT do it this way. Your getApi() method should have a success block which would be executed if the response was successful. Here is one possible solution:

static func getApi(success:( (data:NSArray) -> () )) {

    let user:String = "user"
    let password:String = "password"

    Alamofire.request(.GET, "http://localhost/api/")
        .authenticate(user: user, password: password)
        .responseJSON{ (request, response, jsonData, error) in

            if let jsonData1 = jsonData {

                if let jsonData2 = JSON(jsonData1).dictionaryObject {

                    success(jsonData2 as! NSArray)

                }

            }

    }

    return data

}

So, if you want to print the response, you'll do something like:

APIManager.getApi {
 println($0)
}
avismara
  • 5,141
  • 2
  • 32
  • 56
0

using URLSession you can write your APIManager class like this

import UIKit
import SwiftyJSON

class APIManager: NSObject {

    let baseURL = "https://jsonplaceholder.typicode.com"
    static let sharedInstance = APIManager()
    static let getPostsEndpoint = "/posts/"

    func getPostWithId(postId: Int, onSuccess: @escaping(JSON) -> Void, onFailure: @escaping(Error) -> Void){
        let url : String = baseURL + APIManager.getPostsEndpoint
        let request: NSMutableURLRequest = NSMutableURLRequest(url: NSURL(string: url)! as URL)
        request.httpMethod = "GET"
        print("Request ",request)
        let session = URLSession.shared
        let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
            if(error != nil){
                onFailure(error!)
            } else{
                do {
                    let data = try JSON(data: data!)
                    print("\n Success data ",data)
                    onSuccess(data)
                } catch let error as NSError {
                    print("Error ",error)
                }
            }
        })
        task.resume()
    }
}

// and to use write definition for api call and response in your controller as follows

func getGETAPIData(){
        APIManager.sharedInstance.getPostWithId(postId:1, onSuccess: { json in
            DispatchQueue.main.async {
                print("data in list view:",String(describing: json))
            }
        }, onFailure: { error in
            print("error2 :")
        })
    }

// and call this method as

self.getGETAPIData()
234 Shk
  • 326
  • 1
  • 2
  • 11