首页 > 解决方案 > 从 WordPress 帖子中获取动态图片

问题描述

我有一个 WordPress 帖子,其中包含定期更新的帖子图片。我想在 Swift 中动态查询这个帖子图片,但还没有找到解决方案。有人可以帮助我吗?这是我目前请求常规图像的代码:


   var coursesPicture = [CoursesPicture]()
    // MARK: - GUID

    struct GUIDURL: Codable {
        let rendered: String
    }


    // MARK: - Courses

    struct Course: Codable {
        let guid, title: GUID
        let content: Content
        let links: Links

        enum CodingKeys: String, CodingKey {
            case guid, title, content
            case links = "_links"
        }
    }


    // MARK: - Content

    struct Content: Codable {
        let rendered: String
        let protected: Bool
    }


    // MARK: - GUID

    struct GUID: Codable {
        let rendered: String
    }


    // MARK: - Links

    struct Links: Codable {
    }


    // MARK: - CoursePicture

    struct CoursesPicture: Codable {
        let featuredMedia: Int

        enum CodingKeys: String, CodingKey {
            case featuredMedia = "featured_media"
        }
    }

public func fetchJSONPicture() {
        let urlString = "https://ismaning.de/wp-json/wp/v2/media/4291"
        guard let url = URL(string: urlString) else { return }
        URLSession.shared.dataTask(with: url) { (data, _, err) in
            DispatchQueue.main.sync {
                if let err = err {
                    print("Failed to get data from url:", err)
                    return
                }

                guard let data = data else { return }

                do {

                    self.coursesPicture = [try JSONDecoder().decode(CoursesPicture.self, from: data)]
                } catch let jsonErr {
                    print("Failed to decode:", jsonErr)
                }
            }
        }
        if let url = URL(string: "https://ismaning.de/wp-content/uploads/ismaning-willkommen-banner_app-ios.jpg") {
            URLSession.shared.dataTask(with: url) { (data, urlResponse, error) in
                if let data = data {
                    DispatchQueue.main.sync {
                        self.imageView.image = UIImage(data: data)
                    }
                }
            }.resume()
        }
    }

我只是通过 URL 在这里查询图像。不过,它应该通过 WordPress 帖子动态查询。我也尝试了这个 JSON 查询,但不幸的是我还没有找到解决方案

提前感谢您的帮助,因为我一直在寻找解决方案一段时间

标签: arraysjsonswiftwordpress

解决方案


在聊天中讨论后,我们找到了解决此问题的有效解决方案。如果其他人有这个,你可以简单地这样做:

  1. 创建两个结构,示例Struct Response: Codable{}
  2. 创建两个结构类型的数组,例如:var arr:[Response] = []
  3. 在 ViewDidLoad 中,您将getJsonData使用完成块调用该方法。
  4. 当数据加载到第一个数组中时,您getJsonImage使用完成块调用该方法。
  5. 获得 imageURL 后,您可以通过创建一个URLSession来检索图像来简单地检索它。

这是解决方案代码:

    //Arrays
    var firstArray:[FirstResponse] = []
    var imgData:[ImgData] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        //Fetching the JSON data
        fetchJSON {
            //Fetching the JSON image
            self.fetchJSONImage {
                let imageUrl = self.imgData[0].link
                self.imgView.downloaded(from: imageUrl)
            }
        }
    }

    //Retrieving the JSON data
    func fetchJSON(completed: @escaping () -> ()){
        var urlString = "HIDDEN"
        urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

        guard let url = URL(string: urlString) else {return}

        //Create the URLSession
        URLSession.shared.dataTask(with: url) { (data, response, err) in
            guard let data = data else{
                return
            }
            do{
                //Sets the dataArray to JSON data
                self.firstArray = [try JSONDecoder().decode(FirstResponse.self, from: data)]

                //Complete task in background
                DispatchQueue.main.async {
                    completed()
                }
            }
            catch let jsonErr{
                print(jsonErr)
            }
        }.resume()
    }

    //Retrieving the image link from JSON
    func fetchJSONImage(completed: @escaping () -> ()){
        let imgPath = firstArray[0].featured_media

        var urlString = "HIDDEN-URL\(imgPath)"
        urlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!

        guard let url = URL(string: urlString) else {return}

        //Create the URLSession
        URLSession.shared.dataTask(with: url) { (data, response, err) in
            guard let data = data else{
                return
            }
            do{
                //Sets the dataArray to JSON data
                self.imgData = [try JSONDecoder().decode(ImgData.self, from: data)]

                //Complete task in background
                DispatchQueue.main.async {
                    completed()
                }
            }
            catch let jsonErr{
                print(jsonErr)
            }
        }.resume()
    }

}

//Struct for getting image ID
struct FirstResponse: Codable{
    let featured_media: Int
}

//Struct for getting the image link
struct ImgData: Codable{
    let link: String
}

//Extension
extension UIImageView {

    //Download the image from the API
    func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleToFill) {
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard let image = UIImage(data: data)
                else { return }

            //Continue in background
            DispatchQueue.main.async() {
                self.image = image
            }
        }.resume()
    }
    func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
        guard let url = URL(string: link) else { return }
        downloaded(from: url, contentMode: mode)
    }
}

推荐阅读