Aşağıdaki gibi bir json datasını,
{
"data": [
{
"color": "green",
"color_RGB": {
"blue": "110",
"green": "216",
"red": "169"
},
"color_type": "success",
"comment": "4 ENGINES PERFORMANCE",
"date": "Tuesday, 26th December 2017",
"date_added": "26/12/2017 06:47",
"tag_name": "Completed",
"time": "06:47 AM",
"title": "Completed Course",
"user_message_id": "8620445"
},
{
"color": "light-green",
"color_RGB": {
"blue": "161",
"green": "161",
"red": "161"
},
"color_type": "default",
"comment": "4 ENGINES PERFORMANCE",
"date": "Tuesday, 26th December 2017",
"date_added": "26/12/2017 06:46",
"tag_name": "Continue",
"time": "06:46 AM",
"title": "Completed Study Course",
"user_message_id": "8620439"
},
{
"color": "blue",
"color_RGB": {
"blue": "226",
"green": "172",
"red": "89"
},
"color_type": "primary",
"comment": "EUROPEAN REDUCED VERTICAL SEPARATION MINIMA - EUR RVSM",
"date": "Tuesday, 26th December 2017",
"date_added": "26/12/2017 06:44",
"tag_name": "Entered",
"time": "06:44 AM",
"title": "Entered Exam",
"user_message_id": "8620404"
}
]
}
Swift 4 üzerinde Alamofire kütüphanesi ve Codable Struct yapısını kullanarak aşağıdaki verdiğim örnekte olduğu gibi alabilirsin.
//
// ViewController.swift
// codableWithAlamofire
//
// Created by Yasin TURKOGLU on 28.12.2017.
// Copyright © 2017 Yasin TURKOGLU. All rights reserved.
//
import UIKit
import Alamofire
struct TimeLineModel: Codable {
var data: [tData]
}
struct tData: Codable {
var color: String?
var color_RGB: colorRGB
var color_type: String?
var comment: String?
var date: String?
var date_added: String?
var tag_name: String?
var time: String?
var title: String?
var user_message_id: String?
}
struct colorRGB: Codable {
var blue: String?
var green: String?
var red: String?
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
getData { (error, timeLineModel) in
if let receivedError = error {
print("An error occured: \(receivedError.localizedDescription)")
} else {
if let receivedTimeLineModel = timeLineModel {
receivedTimeLineModel.data.forEach({ (data) in
print(data)
print("\n")
})
}
}
}
}
private func getData( completion: @escaping(Error?, TimeLineModel?) -> Void) {
Alamofire.request("http://test.url", method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseData { (response) in
switch response.result {
case .success(let data):
let decoder = JSONDecoder()
do {
let timeLineModel = try decoder.decode(TimeLineModel.self, from: data)
completion(nil, timeLineModel)
} catch let error {
completion(error, nil)
}
case .failure(let error):
completion(error, nil)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}