Reputation: 280
I'm trying to loop through parsed array the array name is urls in which each element contains id, label, and size here is a picture showing the array
I was able to loop through the array, but what I'm trying to do is to always access the first id in the urls array
Alamofire.request("\(saveItLink)\(requestedLink)\(requestType)", method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
let jsonArray = json["urls"].array
for ids in jsonArray!{
let id = ids["id"].stringValue
print(ids["id"].stringValue)
}
//print("JSON: \(json)")
case .failure(let error):
print(error)
}
Here is what prints out in the consol
How would I always access the first element of the urls array? and how would I save the value alone as a string value?
Upvotes: 0
Views: 43
Reputation: 702
Well, thanks to SwiftyJSON, you can easily get the value like that:
let firstId = json["urls"][0]["id"].stringValue
You haven't mentioned where do you want to save the value, but you can simply use the UserDefaults. E.g:
UserDefaults.standard.set(firstId, forKey: "your_key_for_accessing_the_value")
Also, I would suggest you to check if value is not empty:
let firstId = json["urls"][0]["id"].stringValue
if !firstId.isEmpty {
UserDefaults.standard.set(firstId, forKey: "your_key_for_accessing_the_value")
} else {
debugPrint("Id is empty")
}
Upvotes: 1