0
I’m getting a Json from a link. How do I find its size and how do I assign the "image" key to a String array - var img = [String]()
?
example JSON:
[{"imagem":"textoX","link":"link da webX"},
{"imagem":"textoY","link":"link da webY"},
{"imagem":"textoZ","link":"link da webZ"}]
Picking up JSON and consulting:
func search(query: String) {
guard
let _ = query.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()),
url = NSURL(string: "http://meusite.com.br/app/teste.php?a=1000")
else { return }
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in
guard
let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
let data = data where error == nil
else { return }
dispatch_async(dispatch_get_main_queue()) { () -> Void in
var error: NSError?
let json = JSON(data: data, options: .AllowFragments, error: &error)
if let error = error {
print(error.localizedDescription)
}
//IMPRIMINDO JSON. . .
print("===json start")
print(json)
print("===json end")
//CONSULTANDO JSON. . .
print(json[0]["imagem"]) // CHAVE IMAGEM DA POSIÇÃO 0
print(json[1]["imagem"]) // CHAVE IMAGEM DA POSIÇÃO 1
}
}).resume()
}
I’m using the SwiftJSON.swift
and in the plist
I’m with the App Transport Security Settings
This way it prints in the answer I wish to assign to a [String]:
var int = 0
for (key, subJson) : (String, JSON) in json {
print("=======Passei aqui!!!=======")
print(json[int]["imagem"])
int = int+1
}
Exactly this however, when you include your code in the scope, it gave me an error in the line of goes saying
'Element' (aka '(String, JSON)') is not convertible to '[String:String]'
– CristianCotrena
Oh yes, now I checked in the library what the result of this method is. I edited the answer, see if it now returns correctly.
– Paulo Rodrigues
Thanks for your attention, he identified the for now however, this giving the following error in the if
Cannot subscript a value of type 'JSON' with an índex of type 'String'
– CristianCotrena
So no error however, it does not enter the if
if let imagem: String = subJson["imagem"] as? String
– CristianCotrena
What I’m not getting is to know which object this library is represented because I can’t test here, by the documentation it’s also hard to know. But I made another attempt, considering
json
is a array, as you reported.– Paulo Rodrigues
I am testing with a JSON that has 3 contents in its scope, it is identifying the 3, because it goes 3 times through the for, but what I do not know at the moment and assign the value of json in the vector [String]. I am very lay at SWIFT, I updated the question. At the end of the question based on your answer. It print on the desired values, only I wonder how to assign even.
– CristianCotrena