soroush asamiesfahan
soroush asamiesfahan

Reputation: 27

How can I use a photo after download without having to download it again?(In Swift)

How can I use a photo after download without having to download it again

I download a photo from the server and it works fine But I want to save it somewhere so I can reuse it without downloading it again

I want to download photos and put them on the table But I want to show the picture next time without downloading it again

this is my code

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return soroush.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let Cell =  tableView.dequeueReusableCell(withIdentifier: "frd", for: indexPath) as! MyfriendsCell
    if soroush[indexPath.row].Country == "sssssss" {
        Cell.MainView.backgroundColor = UIColor.init(displayP3Red: 0.239, green: 0.413, blue: 0.949, alpha: 1)
    }
    Cell.FriendScore.text = String(soroush[indexPath.row].Scores)
    Cell.usernshow.text = soroush[indexPath.row].UsernameShow
    let  Fulllink  = soroush[indexPath.row].Image
    Cell.AvatarImage.downloaded(from: Fulllink)
    return Cell
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

and this is the extension in for download images:

extension UIImageView {
    func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {  // for swift 4.2 syntax just use ===> mode: UIView.ContentMode
        contentMode = mode
        URLSession.shared.dataTask(with: url) { data, response, error in
            guard
                let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
                let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
                let data = data, error == nil,
                let image = UIImage(data: data)
                else { return }
            DispatchQueue.main.async() {
                self.image = image
            }
            }.resume()
    }
    func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) {  // for swift 4.2 syntax just use ===> mode: UIView.ContentMode
        guard let url = URL(string: link) else { return }
        downloaded(from: url, contentMode: mode)
    }

}

and these are my codes in ViewdidLoad() :

        if AppDelegate.friends.isEmpty == true {
        Alamofire.request("https://mr-fast.liara.run/MRFast/Api/getFriendlist",method :.post,encoding:JSONEncoding.default,headers: headers).responseJSON { (newresponse) in
            do {

                let decoder = JSONDecoder()
                let responsegame = try decoder.decode([myfriends].self, from: newresponse.data!)
                for each in responsegame {
                    AppDelegate.friends.append(each)
                }

                let ffff = UserID(fullname: self.Fullname, country: "sssssss", scores: Int(self.Score)!, id: "T##String", usernameShow: self.Username, avatar: self.Avatarimage)
                let rrrrrr = Friend(userID: ffff)
                AppDelegate.friends[0].friends.append(rrrrrr)
                for each in AppDelegate.friends[0].friends {
                    let new = myfriendsarray(Country: each.userID.country, Scores: each.userID.scores, IdAgain: each.userID.id, UsernameShow: each.userID.usernameShow, Image: each.userID.avatar, fullname1: each.userID.fullname ?? "")
                    self.soroush.append(new)
                    DispatchQueue.main.async {
                        self.tableview.reloadData()
                    }
                }
                self.soroush.sort(by: { $0.Scores > $1.Scores })
            }catch{
                print("error")
            }
        }
    }else {
        for each in AppDelegate.friends[0].friends {
            let new = myfriendsarray(Country: each.userID.country, Scores: each.userID.scores, IdAgain: each.userID.id, UsernameShow: each.userID.usernameShow, Image: each.userID.avatar, fullname1: each.userID.fullname ?? "")
            self.soroush.append(new)
            DispatchQueue.main.async {
                self.tableview.reloadData()
            }
        }
        self.soroush.sort(by: { $0.Scores > $1.Scores })
    }

Upvotes: 0

Views: 110

Answers (1)

Hoang Nguyen Chi
Hoang Nguyen Chi

Reputation: 171

I have a solution for your problem.

  1. The first time you must download all image
  2. You display image normally. After you convert image to base64 and store us in local ( userdefault, realm, coredata)

The next time when you go to there. You will prioritize load data from local. If you check in your local database have image data you will convert base64 into image to display. incase don't have local database maybe your save process is unsuccessful. you must download again and store again.

Upvotes: 1

Related Questions