0

I want to load image in View did load method without use of Tableview or collectionView , I have URL of Wordpress Rest Api , I tried to load Image using SwiftyJson , I got Row Values of All Images But Image is not Able to Load I Found fatal error: Index out of range, please help me

override func viewDidLoad() {
            super.viewDidLoad()


        let url = NSURL(string: "  ")

        let session = URLSession(configuration: URLSessionConfiguration.default)

        let task = session.dataTask(with: URLRequest(url: url! as URL)) {(data,response , error) -> Void in

            if (error == nil)
            {

                let swiftyJSON = JSON(data!)
                let entrylevel = swiftyJSON["guid"].arrayValue

                print("\(String(describing: entrylevel))")
                let imagearray = entrylevel[0]["rendered"].string!

                let imageurl = NSURL(string:imagearray)

                if let imagedata = NSData(contentsOf: imageurl! as URL)

                {
                    self.img.image = UIImage(data: imagedata as Data)
                    print("image load")

                }       

            }        

        }
        task.resume()
    }

and here is my rest api

[{"id":1509 "date":"2018-02-15T13:33:22", "date_gmt":"2018-02-15T13:33:22" "guid": { "rendered":"http://thenewschef.com/wp-content/uploads/2018/02/startup.jpeg" }

sapna
  • 11
  • 6

1 Answers1

1

guid is a dictionary not array try

let entrylevel = swiftyJSON[0]["guid"]["rendered"].string 

also wrap this in

DispatchQueue.main.async {

   self.img.image = UIImage(data: imagedata as Data)

}   

and it's better using Data instead of NSData

//

OR

struct Root:Decodable {

  let  guid:InnerItem
}

struct InnerItem:Decodable {

   let rendered:String
}

try {
   let items = try JSONDecoder().decode([Root].self, from: data!)

}
catch {

print(error)
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87