Alfi Alfi - 4 months ago 19
Swift Question

How get Single Url From an Array of urls?

This is My Code:

urll = NSURL(string: "http://xxxxxxxxxxx.com/api/?slider=uij6sdnb")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(urll) {(NSData, response, error) -> Void in
do {
let records = try NSJSONSerialization.JSONObjectWithData(NSData!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
for record in records {
// let urlid = Int(record["slide_id"] as! String)
let urimage = record["slide_url"] as! String
self.urls = [urimage]
print(self.urls.count)
}
}

catch {
print("Json Error")

}
}

task.resume()


When I Print :

print(urimage)


it gaves me 4 url like this:

http://sdkladlkasjd1.jpg

http://sdkladlkasjd2.jpg

http://sdkladlkasjd3.jpg

http://sdkladlkasjd4.jpg

When I print:

print(urimage[1])


It gaves me :
'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion

When i put it in another value :

var urls = [String]()
self.urls = [urimage]


and I print:

print(self.urls.count)


it gaves me

1

1

1

1

How on earch I can access one of this urls !?

I want to Show them on imageview but I can !

Answer

As Julian Kniephoff rightly mentioned, you are printing each URL in the for loop, thus you cannot access one particular one. However, there is also another issue, in that you are replacing the urls array with the latest url each time.

To solve this, simply replace the line self.urls = [urimage] with self.urls.append(urimage).

You can then access a particular image outside the for loop by doing something like self.urls[1].

This is also why printing the count of the array returns 1, since each time around you are setting the array to just the one latest element in the loop.

In the end, your code may look something like this

url = NSURL(string: "http://xxxxxxxxxxx.com/api/?slider=uij6sdnb")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url) {(data, response, error) -> Void in
    do {
        let records = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
        for record in records {
            //let urlid = Int(record["slide_id"] as! String)
            let urimage = record["slide_url"] as! String
            self.urls.append(urimage)
        }
        print(self.urls[1]) //Prints http://sdkladlkasjd2.jpg
    }
    catch {
        print("Json Error")
    }
    //print(self.urls[1])
}

task.resume()
Comments