Hoşgeldin. Soru sormak veya cevaplamak için hemen üye ol.
0 oy
383 kez görüntülendi
ios development kategorisinde tarafından

https://ibb.co/cPuPQR
https://ibb.co/k9t15R
https://ibb.co/cUhuQR

Data'ları alabiliyorum .Yasin Hocam araştırmalarımda JSONDecoder().decode... yapıldıgında struct içine veriler atılabiliyor.Fakat ben atınca nil oluyor. // lu alan şeklinde zaten belli. Duz Http yapsam da aynısı oluyor. Burda alamofire kullandım. Aldıgım data'yı nasıl struct'a atabilirim. ?

bir cevap ile ilgili: Json veriyi Struct model için Atma

2 Cevaplar

0 oy
tarafından

paylaştığın ekran görüntülerinde, json verisi içerisinde null'dönen değerler var.

 "user_type_color" : null
 "login_type" : null

ama Data struct'ın içerisinde bu null değerleri tutabilecek bir karşılık yok.
null dönen veya dönebilecek değerler için struct karşılıklarını optional olarak tanımlamalısın.

struct Data: Codable {
.
.
.
var user_type_color: String?
var login_type: String?
.
.
.
}
0 oy
tarafından
tarafından seçilmiş
 
En İyi Cevap

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()
    }
}
...