How to delete cached SDWebImage from a button's imageView - ios

So I have a UIButton whose imageView is set to an image using a download URL. For this purpose I use SDWebImage.
Problem is, when I press the delete button, I want the image to completely disappear but I guess it does not work because the image is still being retrieved from cache. How do I solve this?
class ViewController: UIViewController{
var profileButton: UIButton = {
let button = UIButton(type: .system)
return button
}()
var user: User?
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(profileButton)
profileButton.addTarget(self, action: #selector(handleDelete), for: .touchUpInside)
self.loadUserPhotos()
}
fileprivate func loadUserPhotos(){
let profileImageUrl = self.user?.profileImageUrl1
if let imageUrl = profileImageUrl, let url = URL(string: imageUrl){
SDWebImageManager.shared().loadImage(with: url, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in
self.profileButton.setImage(image?.withRenderingMode(.alwaysOriginal), for: .normal)
}
}
}
#objc func handleDelete(){
self.user?.profileImageUrl1 = ""
self.profileButton.imageView?.image = nil
self.loadUserPhotos()
}
}

To remove the image from UIButton you need to mention the state as well.
self.profileButton.setImage(nil, for: .normal)

You can use :
SDImageCache.shared.removeImage(forKey: url?.description, withCompletion: nil)

Related

Primitive type parameters in Swift Selector function

I want to add dynamic number of buttons to my VC. So i am looping through my buttons array model and instantiating UIButtons. The problem is with adding target to these buttons. I want to pass in a string to the selector when adding a target, however Xcode compiler doesn't let me do that
Argument of '#selector' does not refer to an '#objc' method, property, or initializer
#objc func didTapOnButton(url: String) { }
let button = UIButton()
button.addTarget(self, action: #selector(didTapOnButton(url: "Random string which is different for every bbutton ")), for: .touchUpInside)
Is there any other solution other than using a custom UIButton
I don't think it is possible to do what you are attempting, you can try like this:
var buttons: [UIButton: String] = []
let button = UIButton()
let urlString = "Random string which is different for every button"
buttons[button] = urlString
button.addTarget(self, action: #selector(didTapOnButton), for: .touchUpInside
#objc func didTapOnButton(sender: UIButton) {
let urlString = self.buttons[sender]
// Do something with my URL
}
As I remember UIButton is hashable...
Another option would be to extend UIButton to hold the information you want:
extension UIButton {
private static var _urlStringComputedProperty = [String: String]()
var urlString String {
get {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
return Self._urlStringComputedProperty[tmpAddress]
}
set(newValue) {
let tmpAddress = String(format: "%p", unsafeBitCast(self, to: Int.self))
Self._urlStringComputedProperty[tmpAddress] = newValue
}
}
}
let button = UIButton()
button.urlString = "Random string which is different for every button"
button.addTarget(self, action: #selector(didTapOnButton), for: .touchUpInside
#objc func didTapOnButton(sender: UIButton) {
let urlString = sender.urlString
// Do something with my URL
}

iOS: Set setImageInputs of image slideshow to array of images

I'm using an image slideshow from here:
iconArr = [UIImage(named: "home-min")!,UIImage(named: "category-
min")!,UIImage(named: "settings-min")!,UIImage(named: "contact us-min")!,UIImage(named: "about us-min")!,UIImage(named: "logout")!]
I need to make this array as an image source.
for image in self.iconArr {
let img = image
self.SlideShow.setImageInputs([ImageSource(image: img)])
}
But that is not working, how can I do that?
you should try this way for sure, because you reset inputs in your for-loop
var imageSource: [ImageSource] = []
for image in self.iconArr {
let img = image
imageSource.append(ImageSource(image: img))
}
self.SlideShow.setImageInputs(imageSource)
As sooper stated, can be done this way
let imageSources = self.iconArr.map { ImageSource(image: $0) }
I found a solution from this url [https://stackoverflow.com/a/50461970/5628693][1]
Below is my code working fine :
var imageSDWebImageSrc = [SDWebImageSource]()
#IBOutlet weak var slideshow: ImageSlideshow!
Add below viewDidLoad()
slideshow.backgroundColor = UIColor.white
slideshow.slideshowInterval = 5.0
slideshow.pageControlPosition = PageControlPosition.underScrollView
slideshow.pageControl.currentPageIndicatorTintColor = UIColor.lightGray
slideshow.pageControl.pageIndicatorTintColor = UIColor.black
slideshow.contentScaleMode = UIViewContentMode.scaleAspectFill
// optional way to show activity indicator during image load (skipping the line will show no activity indicator)
slideshow.activityIndicator = DefaultActivityIndicator()
slideshow.currentPageChanged = {
page in
print("current page:", page)
}
let recognizer = UITapGestureRecognizer(target: self, action: #selector(Dashboard.didTap))
slideshow.addGestureRecognizer(recognizer)
} // now add below func
#objc func didTap() {
let fullScreenController = slideshow.presentFullScreenController(from: self)
// set the activity indicator for full screen controller (skipping the line will show no activity indicator)
fullScreenController.slideshow.activityIndicator = DefaultActivityIndicator(style: .white, color: nil)
}
And last step i was getting json data from below alamofire request
Alamofire.request(url, method: .post, parameters: data, encoding: JSONEncoding.default).responseJSON { response in
if(response.value == nil){
}
else {
let json2 = JSON(response.value!)
switch response.result {
case .success:
self.indicator.stopAnimating()
if let details = json2["imgs"].array {
for dItem in details {
let img = dItem["img"].stringValue
let image = SDWebImageSource(urlString: self.imgurl+img)
self.imageSDWebImageSrc.append(image!)
}
self.slideshow.setImageInputs(self.imageSDWebImageSrc)
}
break
case .failure( _):
break
}
}
}
Thanks dude :) happy coding

why does Bundle.main.path(forResource: fileName, ofType: "txt") always return nil?

I want to read a text file line by line and display it on an iOS screen using the example shown here.
Making textView.text optional was the only way I could get readDataFromFile to run. When I click load the function runs but always returns nil. I assume this means the file is not found.
For testing purposes I created the text file in Xcode. I also tried saving it on the desktop as well as in the project folder. Either way it was readable from the project navigator. I also tried creating the file using TextEdit because the app ultimately needs to read text files created outside Xcode.
I’d be grateful if someone can explain why the text file is never found, whether there is something else I need to do in order for the project to find it or if the read function returns nil for some other reason due to the way I have implemented it. Thanks.
EDIT (2)
Thanks for the feedback. In response, I’ve made four minor code changes that allow the text file contents to be written to textView. Changes include: removing the file extension from the filename, adding an array of file names, returning String instead of String? from readDataFromFile and rewriting UITextView in code. This has solved problems I am aware of.
Here's the revised code
import UIKit
class ViewController: UIViewController {
var textView = UITextView()
var arrayOfStrings: [String]?
var fileNameWithExtension = "textFile.txt"
let arrayOfFileNames = ["textFile1.txt", "textFile2.txt", "textFile3.txt", "textFile4.txt", "textFile5.txt"]
var fileName = String()
override func viewDidLoad() {
super.viewDidLoad()
// remove comment in the next statement to test files named in ArrayOfFileNames
// fileNameWithExtension = arrayOfFileNames[4]
fileName = fileNameWithExtension.replacingOccurrences(of: ".txt", with: "")
createTextView()
createButton()
}
func readDataFromFile(fileName: String) -> String {
if let path = Bundle.main.path(forResource: fileName, ofType: nil) {
print(fileName)
do {
let data = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
arrayOfStrings = data.components(separatedBy: .newlines)
textView.text = arrayOfStrings?.joined(separator: "\n")
} catch {
textView.text = "file contents could not be loaded"
}
} else {
print(Bundle.main.path(forResource: fileName, ofType: "txt") as Any)
textView.text = "\(fileName) could not be found"
}
return textView.text
}
func createButton () {
let button = UIButton();
button.setTitle(String("Load"), for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.frame = CGRect(x: 100, y: 10, width: 200, height: 100)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
}
func buttonAction(myButton: UIButton) {
textView.text = readDataFromFile(fileName: fileName)
print(textView.text as Any)
}
func createTextView () {
textView = UITextView(frame: CGRect(x: 20.0, y: 75.0, width: 340.0, height: 400.0))
textView.textAlignment = NSTextAlignment.left
textView.textColor = UIColor.blue
textView.backgroundColor = UIColor.white
self.view.addSubview(textView)
}
}
EDIT (1)
The file is visible in the project navigator. I will assume that means it is in the bundle.
Here is my original code
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var textView: UITextView?
var arrayOfStrings: [String]?
var fileName = "textFile.txt"
override func viewDidLoad() {
super.viewDidLoad()
createButton()
}
func readDataFromFile(fileName: String) -> String? {
if let path = Bundle.main.path(forResource: fileName, ofType: "txt") {
print(fileName)
do {
let data = try String(contentsOfFile: path, encoding: String.Encoding.utf8)
arrayOfStrings = data.components(separatedBy: .newlines)
print(arrayOfStrings as Any)
textView?.text = arrayOfStrings?.joined(separator: "/n")
return textView?.text
} catch {
textView?.text = "file contents could not be loaded"
return textView?.text
}
} else {
print(Bundle.main.path(forResource: fileName, ofType: "txt") as Any)
textView?.text = "\(fileName) could not be found"
return nil
}
}
func createButton () {
let button = UIButton();
button.setTitle(String("Load"), for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.frame = CGRect(x: 100, y: 15, width: 200, height: 100)
button.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
self.view.addSubview(button)
}
func buttonAction(myButton: UIButton) {
print("works")
textView?.text = readDataFromFile(fileName: fileName)
print(textView?.text as Any)
}
textFile.txt
Line 1
Line 2
Line 3
Line 4
Line 5
1) You have mistake in this line:
var fileName = "textFile.txt"
should be:
var fileName = "textFile"
2) Check is your file connected to target:
You should consider adding class bundle owner like this:
Bundle(for: ViewController.self).path(forResource: "fileName", ofType: "txt")
This was implemented from swift 2.0 if I was right.

How to capture UIEvents of UIButton in custom framework?

I create my own framework and in that I need to provide a button and clicking on button I will do something predefined in framework.
Here is my code.
public class WebButton: NSObject {
public func enableWebButton(enable:Bool)
{
if(enable)
{
let appWindow = UIApplication.sharedApplication().keyWindow
let webBtn = UIButton(frame:CGRectMake((appWindow?.frame.size.width)! - 70,(appWindow?.frame.size.height)! - 70,50,50))
let frameworkBundle = NSBundle(forClass: self.classForCoder)
let img = UIImage(named: "btn_icon.png", inBundle: frameworkBundle, compatibleWithTraitCollection: nil)
webBtn.setImage(img, forState: .Normal)
webBtn.layer.cornerRadius = webBtn.frame.size.width / 2;
webBtn.layer.masksToBounds = true
webBtn.addTarget(self, action: "webButtonClick", forControlEvents: .TouchUpInside)
appWindow?.addSubview(webBtn)
print("btn created")
}
}
func webButtonClick()
{
print("btn Clicked")
}
}
In this code, I am getting button on my sample project, but clicking on button, nothing happens.
"btn created"
log is going to print, but
"btn Clicked"
is never going to print.
Please help me to solve this issue.
Thanks in advance.
Try using this code for creating your button and your webButtonClick function:
public func enableWebButton(enable:Bool)
{
if(enable)
{
let appWindow = UIApplication.sharedApplication().keyWindow
let webBtn = UIButton(frame:CGRectMake((appWindow?.frame.size.width)! - 70,(appWindow?.frame.size.height)! - 70,50,50))
let frameworkBundle = NSBundle(forClass: self.classForCoder)
let img = UIImage(named: "btn_icon.png", inBundle: frameworkBundle, compatibleWithTraitCollection: nil)
webBtn.setImage(img, forState: .Normal)
webBtn.layer.cornerRadius = webBtn.frame.size.width / 2;
webBtn.layer.masksToBounds = true
webBtn.addTarget(self, action: "webButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
appWindow?.addSubview(webBtn)
print("btn created")
}
}
func webButtonClick(sender:UIButton!)
{
print("btn Clicked")
}

UIButton.addTarget with swift 3 and local function

I'm trying to generate multiple buttons programmatically. For the moment, here is what I've got :
for i in POIArray {
let newI = i.replacingOccurrences(of: "GPS30", with: "")
let button = UIButton(type: .custom)
button.setImage(UIImage(named: newI), for: .normal)
button.frame.size.height = 30
button.frame.size.width = 30
button.addTarget(self, action: #selector(buttonAction(texte:newI)), for: UIControlEvents.touchUpInside)
XIBMenu?.stackMenuIco.addArrangedSubview(button)
}
and my function :
func buttonAction(texte: String) {
print("Okay with \(texte)")
}
When I remove the parameter 'texte', it's working. The buttons are well added to the stack but I need that parameter to pass a variable. I get a buildtime error :
Argument of '#selector' does not refer to an '#objc' method, property, or initializer
Yes thank you XCode I know that it's not an objc method, because I'm coding in swift!
Anyone knows a way around ?
Here you need to use objc_setAssociatedObject
Add extension in project:-
extension UIButton {
private struct AssociatedKeys {
static var DescriptiveName = "KeyValue"
}
#IBInspectable var descriptiveName: String? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? String
}
set {
if let newValue = newValue {
objc_setAssociatedObject(
self,
&AssociatedKeys.DescriptiveName,
newValue as NSString?,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
)
}
}
}
}
How to use :-
//let newI = i.replacingOccurrences(of: "GPS30", with: "")
button?.descriptiveName = "stringData" //newI use here
How to get parameter :-
func buttonAction(sender: UIButton!) {
print(sender.descriptiveName)
}

Resources