Tell me how you can implement it. We have a link to JSON

urlToRequest = = "formatio.ru/api/v1/events?q=&city_id=&tag_id=&start_date=2015-01-01&end_date"

We have the first function: Accepts a URL written as a String. Returns an object of type NSData (As I understand it, after execution, there is simply raw data)

func getJSON(urlToRequest: String) -> NSData{ return NSData(contentsOfURL: NSURL(string: urlToRequest)) } 

Next, we have 2 function that will process this "raw" data (parsit) Accepts an NSData object, returns an object of type NSDictionary (Choose this data type since it is best suited for storing JSON's)

 func parseJSON(inputData: NSData) -> NSDictionary{ var error: NSError? var dictionaryFullJson: NSDictionary = NSJSONSerialization.JSONObjectWithData(inputData, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary return dictionaryFullJson } 

Further, as I understand it, 1) we must write our dictionaryFullJson to a variable of type NSDictionary in the viewDidLoad () function already (Is this the main function?)

  override func viewDidLoad() { super.viewDidLoad() let storeJSONFromApi = parseJSON(getJSON(urlToRequest: String)) } 

Everything, after launching the application, we have our Json placed in the NSDictioanary in the storeJSONFromApi constant.

Do I understand everything correctly?

Next you need to bring JSON from Dictionary to TableView. How can this be implemented?

Or, after all, “The code written in the global domain is used as an entry point for the program” and you just have to write beyond the boundaries of other functions

 let storeJSONFromApi = parseJSON(getJSON(urlToRequest: String)) 

and it will be executed, as will be the entry point to the program?

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

Put this functionality in a separate class, for example:

 // для удобства создаем typealias, это тот же словарь, но так будет удобнее typealias JSONObject = [String: AnyObject] // реализуем синглтон, для доступа к этому классу из любой части программы class APIController { class var sharedController: APIController { struct Singleton { static let sharedIntance = APIController() } return Singleton.sharedIntance } } // собственно, сами запросы extension APIController { private struct Consts { static let baseURL = "https://formatio.ru/api/v1" static let parsingQueue = dispatch_queue_create("com.MyApp.queues.parsing", nil) } func runAPICall(call: String, params: [String: String], completion: (JSONObject?, NSError?) -> Void) { var paramsString = "" for (key, value) in params { if let paramValue = value.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { if count(paramsString) > 0 { paramsString+="&" } paramsString+="\(key)=\(paramValue)" } } if let url = NSURL(string: call+"?"+paramsString) { NSURLConnection.sendAsynchronousRequest(NSURLRequest(URL: url), queue: NSOperationQueue.mainQueue()) { response, data, error in if let err = error { completion(nil, err) } else { dispatch_async(Consts.parsingQueue) { () -> Void in var parseError: NSErrorPointer = nil let object = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: parseError) as? JSONObject dispatch_async(dispatch_get_main_queue()) { () -> Void in completion(object, nil) } } } } } else { completion(nil, nil) } } } 

here is an example of use:

 class SomeViewController: UITableViewController { // переменная для хранения полученных объектов var items: [JSONObject] = [] override func viewDidLoad() { super.viewDidLoad() // Шлем запрос: APIController.sharedController.runAPICall("events", ["term": "Can't Stop", "attribute": "songTerm", "entity": "album"], completion: { response, error in // тут обрабатываем ответ или ошибку позднее, после его завершения и завершения парсинга switch (error, response?["results"] as? [JSONObject]) { case (.Some(let err), _): // обрабатываем ошибку case (_, .Some(let objects)): // здесь я ожидаю массив, поэтому в switch проверяю, что это массив словарей с помощью 'as? [JSONObject]' self.items = objects self.tableView?.reloadData() default: // нет ошибки или не те данные, обрабатываем } }) } }