如何使用 SwiftyJSON 和 Alamofire 创建 URL 数组?

How can I create an array of URLs with SwiftyJSON and Alamofire?

我遇到以下问题 我需要从 JSON 对象中检索 URL 的数组,以便从我的电子商务网站下载所有产品图片应用

我得到的 JSON 看起来像这样:

  [
{
........
........
.........
........
"images": [
  {
    "id": 976,
    "date_created": "2016-08-10T15:16:49",
    "date_modified": "2016-08-10T15:16:49",
    "src": "https://i2.wp.com/pixan.wpengine.com/wp-content/uploads/2016/07/canasta-familia.jpg?fit=600%2C600&ssl=1",
    "name": "canasta-familia",
    "alt": "",
    "position": 0
  }
], 
.......
.......
.......

到目前为止,我只能从数组中获取一个字符串。

Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
        .responseJSON { response in
 if let jsonValue = response.result.value {
                let jsonObject = JSON(jsonValue)
                var jsonArray = jsonObject[0]["images"][0]["src"].stringValue
                print(jsonArray)
    }
}

这给了我这个

https://xx.xx.xx/xxxx.xxxxx.xxxx/xx-xxxxx/uploads/2016/07/canasta-familia.jpg?fit=600%2C600&ssl=1

但我需要的是访问 "images" 和 "src" 中的所有元素,而不仅仅是两者索引的第一个元素。

我该怎么做?

有什么想法吗?

步骤 1:

创建自定义对象来表示图片。我们称之为 "Picture".

struct Picture {

    let id:Int
    let date_created:String
    let date_modified:String
    let src:String
    let name:String
    let alt:String
    let position:Int
}

第 2 步:

创建一个数组来保存您所有的产品图片。确保注意创建它的范围。理想情况下,它应该在您的下载功能之外。

var productPictures = [Picture]()

第 3 步:

下载您的 JSON 文件,为每张图片创建一个 Picture 结构,然后将每张图片添加到您的 productPictures 数组。

Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
        .responseJSON { response in

            switch response.result {
            case .success:

                self.productPictures.removeAll()

                guard let json = response.result.value as? [String:Any] else {
                    print("couldn't retrieve json as a dictionary")
                    return
                }

                guard let images = json["images"] as? [AnyObject] else {
                    print("there was a problem accessing the images key")
                    return
                }

                for image in images {

                    guard let id = image["id"] as? Int,
                          let date_created = image["date_created"] as? String,
                          let date_modified = image["date_modified"] as? String,
                          let src = image["src"] as? String,
                          let name = image["name"] as? String,
                          let alt = image["alt"] as? String,
                          let position = image["position"] as? Int
                    else {
                        print("There was a problem accessing one of the picture variables, or it was missing")
                        continue
                    }

                    let newPicture = Picture(id: id,
                                             date_created: date_created,
                                             date_modified: date_modified,
                                             src: src,
                                             name: name,
                                             alt: alt,
                                             position: position)

                    self.productPictures.append(newPicture)
                }
            case .failure(let error):
                print("could not download and retrieve product images. An error occurred: \(error)")
                return
            }
    }

现在您有一个充满图片结构的数组,每个结构都包含从您的 JSON 下载中提取的所有必要信息。

备注

这没有使用 SwiftyJSON,但它应该可以工作并为您提供相同的预期结果。希望对您有所帮助!

以下代码行应该可以工作,因为我已经用实际数据集测试了自己。

import Alamofire
import SwiftyJSON

Alamofire.request(url, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers)
    .responseJSON { response in
    if let jsonValue = response.result.value {
        let jsonObject = JSON(jsonValue)
        if let array = jsonObject.array {
            for i in 0..<array.count {
                if let images = array[i]["images"].array {
                    for i in 0..<images.count {
                        let src = images[i]["src"]
                        print(src) // save src in an array or whatever
                    }
                }
            }
        }       
    }