How to clear uimage from cache in swift? - ios

I am working on my first app with the different figures, appearing on screen. Firstly it should be stars and in the next round cirles. The problem is: the new figures appear properly, but the previous ones don't disappear. I read in internet that the problem may be that they stay in cache. The suggested solution was to use UIImage(contentsOfFile:..) instead of UIImage(named:..). I try to follow it but result is the same.
Here is my code:
func chooseFigure() {
switch (countRound-1) {
case 0 :
let path = NSBundle.mainBundle().pathForResource("star", ofType: "png")
let image = UIImage(contentsOfFile: path!)
thisCard.image = image!.imageWithRenderingMode(.AlwaysTemplate)
case 1 :
let path = NSBundle.mainBundle().pathForResource("circle", ofType: "png")
let image = UIImage(contentsOfFile: path!)
thisCard.image = image!.imageWithRenderingMode(.AlwaysTemplate)
default:
cards[0].backgroundColor = UIColor.blackColor()
}

I think I have it. The problem was not in cache (thanks for the idea, Abhishek Biswas and Arun Basil Issac). All I need to do was to delete the old subviews before I load the new ones.
Here is the code:
for view in layout.layoutMid.midSubView.subviews {
view.removeFromSuperview()
}

Try using to delete or hide the previous state before starting the present state. Use if-else inside the cases.

Related

How to put animating placeholder image while downloading url image in swift 4 or Swift 5

I did try with Cocapods "Kingfisher" but cannot figure out how to set an animating placeholder image while the image is being downloaded.
here is the Below code I tried with kingfisher Pod
func configureCell(category:Category){
if let url = URL(string: category.imgUrl){
let placeholder = UIImage(named: "placeholder")
let options : KingfisherOptionsInfo = [KingfisherOptionsInfoItem.transition(.fade(0.1))]
categoryImg.kf.indicatorType = .activity
categoryImg.kf.setImage(with: url, placeholder: placeholder, options: options)
}
}
This is actually not an image but a UIView. The best option would be to use SkeletonView.
SkeletonView has been conceived to address this need, an elegant way to show users that something is happening and also prepare them to which contents he is waiting.
This animation is called Shimmer effect . You can use this link for your help
facebook/Shimmer.

Sharing a story to Instagram with a background image and a sticker - IOS Swift

I'm trying to share a story with a background image a a sticker image via URL Scheme on my ios app, i am using the attached code and it dose not work.
When i'm trying to share just a background image or just a sticker it does work. But when im trying share both a background image and a sticker in top of it, it dose not work.
Any Ideas?
func shareToInstagram(deepLinkString : String){
let url = URL(string: "instagram-stories://share")!
if UIApplication.shared.canOpenURL(url){
let backgroundData = UIImageJPEGRepresentation(UIImage(named: "shop_placeholder")!, 1.0)!
let creditCardImage = UIImage(named: "share_instagram")!
let stickerData = UIImagePNGRepresentation(creditCardImage)!
let pasteBoardItems = [
["com.instagram.sharedSticker.backgroundImage" : backgroundData],
["com.instagram.sharedSticker.stickerImage" : stickerData],
]
if #available(iOS 10.0, *) {
UIPasteboard.general.setItems(pasteBoardItems, options: [.expirationDate: Date().addingTimeInterval(60 * 5)])
} else {
UIPasteboard.general.items = pasteBoardItems
}
UIApplication.shared.openURL(url)
}
I copy pasted OP's code for use in my own app (only substituting different UIImages) and found only 1 issue, pasteboard items should be contained in a single array otherwise instagram will render only the first item (in this case the background layer). To fix this, replace the declaration of pasteboard items with the following code
let pasteBoardItems = [
["com.instagram.sharedSticker.backgroundImage" : backgroundData,
"com.instagram.sharedSticker.stickerImage" : stickerData]
]
(basically just remove the close and open bracket separating the two items)
Also as a previous answer stated, make sure "instagram-stories" is included in LSApplicationQueriesSchemes in the info.plist file
I use this exact code in my app and it now works perfect
Everything is correct, my code is similar and it works for iOS 11+. I suggest you the following:
check the image data you pass to pasteboard (jpg can't be converted with
UIImagePNGRepresentation and vice versa)
check the info.plist. You should enable "instagram-stories" scheme in it (LSApplicationQueriesSchemes key)
Like Alec said, you need to put all of Instagram data in one list, not multiple lists. look at the example from the meta documents:
NSArray *pasteboardItems = #[#{#"com.instagram.sharedSticker.stickerImage" : stickerImage,
#"com.instagram.sharedSticker.backgroundTopColor" : backgroundTopColor,
#"com.instagram.sharedSticker.backgroundBottomColor" : backgroundBottomColor}];
2. For more recent readers, as of swift 4.2 and iOS 12 UIImageJPEGRepresentation is replaced by jpegData. change
let backgroundData = UIImageJPEGRepresentation(yourImage, 1.0)
with
let backgroundData = yourImage.jpegData(compressionQuality: 1.0)

Adding image from Firebase to UITableViewCell

I want to retrieve the image that is stored in the storage of an user and place it next to his name in a custom UITableViewCell. The problem now is that the tableview will load when the images aren't done downloading (I think?), causing the application to crash because the image array is nil. So what is the correct way to load the tableview? I think, for the user experience, it is important that the tableviewcell image should be shown even if the images aren't done downloading, and present them a default image that is saved in the assists. I thought about making an array with UIImages that links to the default asset of loading an image and changing the image to the profile picture when it is done downloading. But I really have no clue how to do that. This is what I got so far about downloading the image:
let storage = FIRStorage.storage()
let storageRef = storage.reference(forURL: "link.appspot.com")
channelRef?.observeSingleEvent(of: .value, with: { (snapshot) in
if let snapDict = snapshot.value as? [String:AnyObject]{
for each in snapDict{
let UIDs = each.value["userID"] as? String
if let allUIDS = UIDs{
let profilePicRef = storageRef.child((allUIDS)+"/profile_picture.png")
profilePicRef.data(withMaxSize: 1 * 500 * 500) { data, error in
if let error = error {
}
if (data != nil)
{
self.playerImages.append(UIImage (data: data!)!)
}
}
}
let userNames = each.value["username"] as? String
if let users = userNames{
self.players.append(users)
}
}
}
self.tableView.reloadData()
})
This is in the cellForRow
cell.playersImage.image = playerImages[indexPath.row] as UIImage
My rules, haven't changed it from the default rules:
service firebase.storage {
match /b/omega-towers-f5beb.appspot.com/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
Thank you.
Regarding user experience, you are correct. It is standard to have some sort of default image when loading an image from a URL. A great library to use for image caching and using default assets in its' place is AlamofireImage
Vandan Patel's answer is correct in saying you need to ensure your array is not nil when loading the tableview. You will be given a completion block to handle any extra work you would like to do with your image, using the AlamofireImage library.
This is all assuming you are getting a correct image URL back for your Firebase users.
You should call tableView.reloadData() when the images are done downloading. One important thing, initialize your playerImages as playerImages = [UIImage]() instead of playerImages: [UIImage]!. if it's empty, it wouldn't show your array is nil.
Update:
if let players = playerImages {
//code
}

Load image from folder inside project

I'm making an app with the folder like image below:
As you can see in this picture, Stickers folder have 2 sub folder "1" and "2". In side them is bunch of icon and I wanna load it in a collection view with each sub folder is a package of different sticker. For more details, please see this picture:
So, how can I get it in my project folder? I've read about access document directory but seem like it not solve my problem.
Please help me. Thanks in advance.
Look at Filemanagers API. It offers all you need.
Example to get content at path:
let pathToDir1 = Bundle.main.resourcePath! + "/Stickers/1";
let fileManager = FileManager.default
let contentOfDir1 = try! fileManager.contentsOfDirectory(atPath: pathToDir1)
Example to iterate over:
let docsPath = Bundle.main.resourcePath!
let enumerator = fileManager.enumerator(atPath:docsPath)
let images = [UIImage]()
while let path = enumerator?.nextObject() as! String {
let contentOfCurDir = try! fileManager.contentsOfDirectory(atPath: path)
// do whatever you need.
}
For details see Apples documentation and sample code.
If you're looking to access an image within your project folder you simply need to use the image name. You don't need to define the whole path.
Objective-C
UIImage *img = [UIImage imageWithName:#"IMAGE_NAME"];
swift
var img = UIImage(named:"IMAGE_NAME")

exc-bad-instruction code=i386_invop

I'm getting this error in latest version of xcode using swift 2
on line
let s = linkTxt.text
Text in linkTxt appears by button "pasteFromClipBoard"
let s = linkTxt.text
let u = NSURL(string: s!)
let file = u?.lastPathComponent
What is the reason of it and how to fix it?
Update:
the problem appears in function saveData() which calls when file downloading is finished. It calls from NSURLSessionDataTask function. More interesting, that in start-downloading-button there are the same lines where filename is generating and there is no such error on it. I fixed these issues by declaring variables, writing text's values into them and use these variables in saveData() except textObject.text; I had to delete lines with NSUserDefaults from saveData() too because I got the same error. Did understand nothing >_<
Update 2:
It's really a bug. I've deleted this line and wrote again - problem fixed
linkTxt.txt is returning nil and NSURL(string: s!) will try to forcefully unwrap it.
let s = linkTxt.text
if let s = linkTxt.txt {
let u = NSURL(string: s!)
let file = u?.lastPathComponent
}

Resources