Ios 阿拉莫菲尔附加数据
我有一个简单的Alamofire请求,我正在用SwiftyJSON解析它。以下是代码:Ios 阿拉莫菲尔附加数据,ios,swift,alamofire,Ios,Swift,Alamofire,我有一个简单的Alamofire请求,我正在用SwiftyJSON解析它。以下是代码: var fetchedData: [TestDB]? = [] func fetchData() { Alamofire.request(url!, method: .get).validate().responseJSON { response in switch response.result { case .success(let value):
var fetchedData: [TestDB]? = []
func fetchData() {
Alamofire.request(url!, method: .get).validate().responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
self.fetchedData = [TestDB]()
for dict in json["articles"].array! {
let data = TestDB()
if let image = dict["urlToImage"].string {
data.imageUrls = image
}
if let titlee = dict["title"].string {
data.titlee = titlee
}
if let desc = dict["description"].string {
data.desc = desc
}
self.fetchedData?.append(data)
// If i print fetchedData here, i can see it has right values.
// print(fetchedData)
}
case .failure(let error):
print(error)
}
}
// If i try to print fetchedData here, it's empty.
}
正如我在代码中所说,我不能附加和使用我的数据。我认为这是阿拉莫菲异步的原因。但我不知道为什么。感谢您的帮助。谢谢 当您使用异步方法时,您有一些方法可以继续,例如:
- 使用回调
- 使用RAC/观察
func fetchData(completion: (result: [TestDB]) -> ) {
Alamofire.request(url!, method: .get).validate().responseJSON { response in
self.fetchedData = [TestDB]()
// fill self.fetchedData then:
completion(self.fetchedData)
}
})
在其中调用fetchData:
self.fetchData(completion: {
// update collectionview?
self.collectionView.reloadData()
})
RAC:
您可以找到所有文档
加号:
一些建议:
- self.fetchedData=TestDB不是必需的,可能是足够的self.fetchData.removeAll()
- 用于将任何json响应映射到对象
- 使用回调
- 使用RAC/观察
func fetchData(completion: (result: [TestDB]) -> ) {
Alamofire.request(url!, method: .get).validate().responseJSON { response in
self.fetchedData = [TestDB]()
// fill self.fetchedData then:
completion(self.fetchedData)
}
})
在其中调用fetchData:
self.fetchData(completion: {
// update collectionview?
self.collectionView.reloadData()
})
RAC:
您可以找到所有文档
加号:
一些建议:
- self.fetchedData=TestDB不是必需的,可能是足够的self.fetchData.removeAll()
- 用于将任何json响应映射到对象