从AlamoFire导入JSON数据后创建数组

时间:2018-10-25 08:40:31

标签: ios json swift alamofire

我正在进行API调用,但是响应正确返回。这是一系列youtube链接:

"items": [
  {
   "kind": "youtube#playlistItem",
   "etag": "\"XI7nbFXulYBIpL0ayR_gDh3eu1k/1GDmRHbln92JxGtet7SSiPs9SaY\"",
   "id": "UEw1dHZnblY0RmtqMHdpeFZ0bmNLZklqMEZuZEZmRUpYdS41NkI0NEY2RDEwNTU3Q0M2",
   "snippet": {
    "publishedAt": "2018-10-17T22:37:35.000Z",
    "channelId": "UCf-gdftRGql5XOUd_ZpVnZg",
    "title": "A Republican, Democrat, and Independent Drink Together | Strange Brew | ",
url:www.test url
}
    }
    }
    ]

具有加载视频的功能:

视频类:UIViewController,UITableViewDelegate,UITableViewDataSource {

var video = [LicenseDetails]()
let recVideos = NSURL(string: RecVideos)





func loadVideos() {
Helpers.showActivityIndicator(activityIndicator, view)

APIManager.shared.recVideos { json in
        if json != nil {
            self.video = []

            print("Lookin In", json)

//            Adds all items into the array list dist then goes through them all.
            if let listDis = json["items"].array {
                print("Looking For Items", listDis)

                for item in listDis {

                    let Video = LicenseDetails(json: item)
                    self.video.append(Video)
                    print("Test: ", self.video)

                }

                Helpers.hideActivityIndicator(self.activityIndicator)

            }
            }
        }
    }

我正在尝试解析通过LicenseDetail类传入的数据

class LicenseDetails {

    var title: String?
    var url: String?
    var videoId: String?



    init(json: JSON) {

        self.title = json["title"].string
        self.videoId = json["resourceId"]["videoId"].string

    }
}

我不明白为什么我不能用JSON信息中的数据填充listDis数组,然后用我的LicenseDetail(json:json)方法对其进行解析。请协助。

1 个答案:

答案 0 :(得分:0)

首先请确保初始化所有存储的属性。而且您需要将Json数据转换为字符串。我使用Swift的投放方式。使用amofire就像您所写的那样或类似self.title = json["title"].stringValue

struct LicenseDetails {
    var title: String
    var url: String
    var videoId: String

    init(json: JSON) {
        self.title = json["title"] as! String
        self.url = json["title"] as! String
        self.videoId = json["videoId"] as! String
    }
}

接下来,仅将JSON提取部分留给loadVideos()函数,并将其余部分移至ViewController并为其设置初始化,如下所示:

class Video: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var videos = [LicenseDetails]()
    required init(json: JSON) throws {
        super.init()
        let listDis = json["items"].array
        self.videos = listDist.map{LicenseDetails(json:$0)}
    }
}

就是这样。希望它能工作。