arrays - 从 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 查询,但不幸的是我还没有找到解决方案
提前感谢您的帮助,因为我一直在寻找解决方案一段时间
解决方案
在聊天中讨论后,我们找到了解决此问题的有效解决方案。如果其他人有这个,你可以简单地这样做:
- 创建两个结构,示例
Struct Response: Codable{}
- 创建两个结构类型的数组,例如:
var arr:[Response] = []
- 在 ViewDidLoad 中,您将
getJsonData
使用完成块调用该方法。 - 当数据加载到第一个数组中时,您
getJsonImage
使用完成块调用该方法。 - 获得 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)
}
}
推荐阅读
- javascript - 如何在反应钩子中修复部门上的显示列表
- docker - 如何使用 Bamboo 从经过身份验证的注册表中将 Docker 映像提取到 ECR 中的特定存储库?
- kubernetes - 无法通过主节点 IP 访问在工作节点上运行的 Kubernetes pod
- java - 无法启动tomcat(org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading非法访问:)
- python - python多处理管理器连接创建另一个对象
- powershell - Powershell:写入单个日志文件
- java - pkcs#10 请求的格式,EJBCA
- angular - Angular 7:TypeError:构建生产代码时无法读取未定义的属性“种类”
- aem - 如何将 favicon 添加到 AEM 资产,例如 pdf/视频
- android-tv - 是否可以在安卓电视平台上开发一款类似 Netflix app 风格的 app?