У меня есть ответ JSON ниже, и я хочу получить идентификатор для объектов попадания:
{
"totalHits":500,
"hits":[
{
"largeImageURL":"https://pixabay.com/get/ea32b90a2af3073 ... 0_1280.jpg",
"webformatHeight":426,
"webformatWidth":640,
"likes":0,
"imageWidth":4494,
"id":3785276,
"user_id":10546560,
"views":21,
"comments":0,
"pageURL":"https://pixabay.com/en/port-river-liner ... e-3785276/",
"imageHeight":2996,
"webformatURL":"https://pixabay.com/get/ea32b90a2af3073 ... b0_640.jpg",
"type":"photo",
"previewHeight":99,
"tags":"port, river, liner",
"downloads":9,
"user":"LunevAndrey",
"favorites":0,
"imageSize":3306757,
"previewWidth":150,
"userImageURL":"",
"previewURL":"https://cdn.pixabay.com/photo/2018/10/3 ... 76_150.jpg"
}
]
}
Вот что у меня есть на данный момент:
import UIKit
import SDWebImage
class Model: NSObject {
var title : Any!
init (dict : [String:Any]) {
self.title = (((dict as AnyObject)["hits"] as! [String:AnyObject])) ["id"] as? Any
}
}
И в контроллере представления у меня есть следующий код:
import UIKit
import Alamofire
class CollectionView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
let url1 = ["URL path string"]
@IBOutlet weak var collection: UICollectionView!
var arrList = [Model]()
override func viewDidLoad() {
super.viewDidLoad()
reequest()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.collection.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: firstCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! firstCollectionViewCell
let objct = arrList[indexPath.row]
cell.label.text = objct.title as AnyObject as? String
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.view.frame.size.width - 5 * 3 ) / 2 //some width
let height = width * 1.34 //ratio
return CGSize(width: width, height: height)
}
func reequest() {
let url = URL(string: "URL path string")
Alamofire.request(url!).responseJSON {(response) in
switch (response.result){
case .success:
if let data = response.result.value{
if let arrdata = data as? [[String:Any]]{
for dataList in arrdata {
print(dataList)
let obj = Model(dict: dataList)
self.arrList.append(obj)
self.collection.reloadData()
}
}
}
case .failure(let error):
print("error to print the data \(error)")
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/531 ... with-array
Анализ данных JSON из Alamofire в словарь с помощью Array ⇐ IOS
Программируем под IOS
-
Anonymous
1737131069
Anonymous
У меня есть ответ JSON ниже, и я хочу получить идентификатор для объектов попадания:
{
"totalHits":500,
"hits":[
{
"largeImageURL":"https://pixabay.com/get/ea32b90a2af3073ed1584d05fb1d4190e070e4d71aac104491f1c270a0eeb7b0_1280.jpg",
"webformatHeight":426,
"webformatWidth":640,
"likes":0,
"imageWidth":4494,
"id":3785276,
"user_id":10546560,
"views":21,
"comments":0,
"pageURL":"https://pixabay.com/en/port-river-liner-sea-cruise-3785276/",
"imageHeight":2996,
"webformatURL":"https://pixabay.com/get/ea32b90a2af3073ed1584d05fb1d4190e070e4d71aac104491f1c270a0eeb7b0_640.jpg",
"type":"photo",
"previewHeight":99,
"tags":"port, river, liner",
"downloads":9,
"user":"LunevAndrey",
"favorites":0,
"imageSize":3306757,
"previewWidth":150,
"userImageURL":"",
"previewURL":"https://cdn.pixabay.com/photo/2018/10/31/06/55/port-3785276_150.jpg"
}
]
}
Вот что у меня есть на данный момент:
import UIKit
import SDWebImage
class Model: NSObject {
var title : Any!
init (dict : [String:Any]) {
self.title = (((dict as AnyObject)["hits"] as! [String:AnyObject])) ["id"] as? Any
}
}
И в контроллере представления у меня есть следующий код:
import UIKit
import Alamofire
class CollectionView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
let url1 = ["URL path string"]
@IBOutlet weak var collection: UICollectionView!
var arrList = [Model]()
override func viewDidLoad() {
super.viewDidLoad()
reequest()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
self.collection.reloadData()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: firstCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! firstCollectionViewCell
let objct = arrList[indexPath.row]
cell.label.text = objct.title as AnyObject as? String
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.view.frame.size.width - 5 * 3 ) / 2 //some width
let height = width * 1.34 //ratio
return CGSize(width: width, height: height)
}
func reequest() {
let url = URL(string: "URL path string")
Alamofire.request(url!).responseJSON {(response) in
switch (response.result){
case .success:
if let data = response.result.value{
if let arrdata = data as? [[String:Any]]{
for dataList in arrdata {
print(dataList)
let obj = Model(dict: dataList)
self.arrList.append(obj)
self.collection.reloadData()
}
}
}
case .failure(let error):
print("error to print the data \(error)")
}
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/53149004/parsing-json-data-from-alamofire-into-dictionary-with-array[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия