简体   繁体   中英

how to load image From Rest Api Into View did Load Method Using Swift 3

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" }

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM