Haneke
A lightweight zero-config image cache for iOS, in Objective-C.
I got a button named "avatarImage" that should display the user's avatar
tried this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//do other cell stuff....
//does not present anything, but actually gets the image!
cell.avatarImage.imageView!.contentMode = .ScaleAspectFill
cell.avatarImage.imageView!.frame = cell.avatarImage.frame
cell.avatarImage.imageView!.hnk_setImageFromURL(imgURL!)
//let foo = UIImageView(frame:cell.frame)
//self.view.addSubview(foo)
//foo.hnk_setImageFromURL(imgURL!)
//tried this for testing, works perfectly fine
}
also when adding a 'UIImageView' to the cell, it will be set correctly. Is there any issue that you can not target button.imageview? directly?
Any hints?
Source: (StackOverflow)
I'm fetching about 136 images, each one about 500 KB, in order to have them cached on the disk.
After downloading image #98, I start getting the following error for the images left (which makes me think they aren't getting cached).
2015-07-29 09:52:44.471 MyProject[299:3418965] [HANEKE][ERROR] Failed to get data for key https://s3.amazonaws.com/my_bucket/my_image_n_99.jpg
Jul 29 09:52:45 my.host.net MyProject[299] <Error>: CGBitmapContextInfoCreate: unable to allocate 31492608 bytes for bitmap data
MyProject(299,0xb039f000) malloc: *** mach_vm_map(size=31494144) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
My first guess was the memory cache filled up, so I called HanekeSwift's Cache.onMemoryWarning()
(had to make it public
) since it has the following implementation:
for (_, (_, memoryCache, _)) in self.formats {
memoryCache.removeAllObjects()
}
But even tho I called it (and supposedly it should clear the memory cache), I still get the error, so I don't know what's wrong.
Any ideas?
Source: (StackOverflow)
I'm trying to cache json I get back from a service using HanekeSwift but I get a syntax error saying "Cannot invoke 'set' with an argument list of type '(value: JSON, key:String, formatName: String, success: (_) -> _)'"
Here is my code for setting the cache:
let cache = Shared.JSONCache
var myJON = SwiftyJSON.JSON(responseData)
cache.set(value: myJSON, key: "key", formatName: HanekeGlobals.Cache.OriginalFormatName, success: {resultData in
})
This worked fine for me when I cached images as NSData. Only difference now is that my cache is a Shared.JSONCache and the value is of JSON type.
Source: (StackOverflow)
In SDWebImage it is possible to prefetch (early loading) images upfront like this:
[[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:<NArray with image URLs>];
Is there a way to achieve the same with Haneke, please?
It seems there is a Preload policy, but unsure how to utilise it, e.g. HNKPreloadPolicyAll
Source: (StackOverflow)
I want to use Carthage in my projects, so i installed carthage. I prepared Cartfile in project's root folder. When I type carthage update command on terminal, i got this error
- *** Cloning HanekeSwift
- No tagged versions found for github "Haneke/HanekeSwift"
Cartfile file contains these:
- github "Alamofire/Alamofire" >= 1.2
- github "Haneke/HanekeSwift"
Waiting for suggestions. Thanks in advice
Source: (StackOverflow)
I am developing an app that fetches images from Twitter using the Haneke library. Once I get the images, I display them using a UITableView. I fetch 10 pictures at a time. My app loads but quickly crashes due to a memory leak.
The code I am using to set the images is as follows.
var tweetImage = "http://pbs.twimg.com/media/CGe89eqWQAACBxR.jpg"
if let var urlString = tweetImage {
var url = NSURL(string: urlString)
cell.tweetImage?.sizeToFit()
cell.tweetImage?.hnk_setImageFromURL(url!)
}
When I comment out the last line cell.tweetImage?.hnk_setImageURL(url!)
I no longer receive the memory warnings and it does not crash.
This is the first app I have ever worked on or made, what is the best way to go about fixing this memory problem? Or am I possibly using the Haneke library wrong?
Thanks in advance, above is the output from Instruments if that helps.
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell= tableView.dequeueReusableCellWithIdentifier("tweetCell", forIndexPath: indexPath) as! TweetTableViewCell
if (indexPath.row % 2 == 0){
cell.backgroundColor = UIColor.whiteColor()
}else{
cell.backgroundColor = UIColor(red: 0.973, green: 0.973, blue: 0.973, alpha: 1)
}
var row = self.results[indexPath.row]
var text = row["text"].string
var name = row["name"].string
var image = row["image"].string
var avatar = row["avatar"].string
var votes = row["rank"].int
var long = row["long"].string
var lat = row["lat"].string
var id = row["id"].int
var tweetImage = image == nil ? avatar : image
if let urlString = tweetImage {
var url = NSURL(string: urlString)
cell.tweetImage?.sizeToFit()
cell.tweetImage?.hnk_setImageFromURL(url!)
}
return cell
}
Above is my cellForRowAtIndexPath method, so far I am just working with the images. self.results
is loaded from an api with the AlamoFire Library
Source: (StackOverflow)
I created a table view which loads contents from a web service. I followed this tutorial so when the user scrolls down more content is loaded. This worked but when I introduced images, it became very clunky.
I saw Haneke seemed to optimise loading images in table views so I added that to my project with cocoapods.
I followed instrictions on git i.e. added a prototype cell with a uiImageView and a label and gave them the associated tags i.e. 101, 103.
However my images are not loading. I am printing out the pic response of my web service and can see there are urls there. What am I doing wrong?
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
if self.members != nil && self.members!.count >= indexPath.row
{
let members = self.members![indexPath.row]
cell.textLabel?.text = members.fName! + " " + members.sName!
cell.detailTextLabel?.text = members.followedId
/*if members.pic != nil {
if let url = NSURL(string: members.pic!) {
cell.imageView?.contentMode = UIViewContentMode.ScaleAspectFit
cell.imageView?.hnk_setImageFromURL(url)
}
}*/
// the commented code above loaded images but scrolling was too clunky
if members.pic != nil {
println("pics are here " + members.pic!)
if let imageView = cell.viewWithTag(101) as? UIImageView {
if let urlString = members.pic{
let url = NSURL(string: urlString)
imageView.hnk_setImageFromURL(url!)
}
}
}
// See if we need to load more members
let rowsToLoadFromBottom = 6;
let rowsLoaded = self.members!.count
if (!self.isLoadingMembers && (indexPath.row >= (rowsLoaded - rowsToLoadFromBottom)))
{
let totalRows = self.membersWrapper!.count!
let remainingMembersToLoad = totalRows - rowsLoaded;
if (remainingMembersToLoad > 0)
{
self.loadMoreFollowedMembers()
}
}
}
return cell
}
Source: (StackOverflow)
I'm currently using the Haneke library and the problem I am having is that the data that should persist after being set, is returning nil
when I fetch the data after I quit and rerun the app.
In my AppDelgate file, outside the class instantiation, I have:
let currentUserCache = Shared.dataCache
On initial login, I store all user information into this cache. I set the User ID like so:
let userIdData = (userIdToData as NSString).dataUsingEncoding(NSUTF8StringEncoding)
currentUserCache.set(value: userIdData!, key: "userId")
Once I quit the app and rerun it, the app should by pass the login screen and immediately send the user to their profile page.
However, prior to this, I send a quick GET request to the server to check whether or not their authentication token is still valid (because there is a timer on it). If it is, then I would like to take user information in the cache and populate the profile. Otherwise I would like to send the user back to the login page. It's when I make this request that I'm running into issues. The userID which I use to make the request keeps spitting out nil
.
currentUserCache.fetch(key: "userId").onSuccess{ data in
var datastring = NSString(data: data, encoding: NSUTF8StringEncoding)
userURL = "URLGOESHERE"
}
Any and all advice is very appreciated!
Source: (StackOverflow)
I used the Haneke Framework to get Data from a Site.
With the Haneke Framework i also can get Images from a site, and these Images i can present on a UIImageView.
Now i wanted to get some text from a site.
I did it like this:
cache.fetch(URL: URL).onSuccess { JSON in
println(JSON.dictionary?["index"])
It printed me all the data from "Index".
Now i want, that all the data from "Index" should be presented on a UITextView.
self.textView.text = JSON.dictionary["index"]
But it doesn't work. I get the error:
Cannot assign a value of type 'AnyObject' to a value of type 'String!'
I have to unwrap it or?
Source: (StackOverflow)
I'm trying to pre-load some images with the following code:
let thumbnailUrl = NSURL(string: urlString)
let fetcher = NetworkFetcher<UIImage>(URL: thumbnailUrl)
Shared.imageCache.fetch(fetcher) {
println("Finished")
}
But afterwards when I try to set it to the imageview, it downloads it again from the network instead of reading it from the cache. This is the code:
self.imageView.hnk_setImageFromURL(
NSURL(string: urlString)
success: { thumbnail in
println("Finished setting image")
}
)
Is this a bug or maybe I missunderstood the usage of imageCache.fetch()
?
PD: I put breakpoints in the whole code, and I can guarantee the key for the cache (in this case, the url) is exactly the same, so I have no clue why the cache isn't resolving when used with .hnk_setImageFromURL()
Source: (StackOverflow)
I'm beginner in xcode and swift, So I'm try to add Haneke
framework to my project. I do these steps:
- Drag
Haneke.xcodeproj
to your project in the Project Navigator.
- Select your project and then your app target. Open the Build Phases panel.
- Expand the Target Dependencies group, and add Haneke.framework.
- Click on the + button at the top left of the panel and select New Copy Files Phase. Set Destination to Frameworks, and add Haneke.framework.
import Haneke
whenever you want to use Haneke
.
But I get this error in improt Haneke
:
No such module 'Haneke'
Also I'm tried to Clean and Build again but not work for me!
Is there a mistake from me?
Edit:
More Info
I used swift 2.0 and xcode 7.0.1 and development target is 8.0
Also I added some screenshots
Source: (StackOverflow)
I tried hnk_setImageFromURL but it says "Value of type 'UIImageView' has no member 'hnk_setImageFromURL'.
I have imported the Haneke.xcodeproj manually. On top of the class there is 'import Haneke'.
Source: (StackOverflow)
I am using Alamofire to perform all network API calls to get a bunch of different JSON files (depending on the view the user is on).
Some of the JSON gets user profile details, some user settings, some data for a tableview.
I am using the below
let postParameters: [String: AnyObject] = ["apiKey":"\(Constants.Variables.apiKey)",
"domain":"\(Constants.Variables.apiDomain)",
"authToken":"\(authToken)",
"password":"\(password)",
"from":"\(from)",
"to":"\(to)"]
Alamofire.request(Router.GetActivities(postParameters))
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { response in
if response.result.isSuccess {
let responseJSON = JSON(response.result.value!)
}
}
and I have a router set up
enum Router: URLRequestConvertible {
static let baseURLString = "\(Constants.APIPath.URL)"
static var OAuthToken: String?
case GetActivities([String: AnyObject])
var method: Alamofire.Method {
switch self {
case .GetActivities:
return .GET
}
}
var path: String {
switch self {
case .GetActivities(_):
return "/activity.php/get"
}
}
var URLRequest: NSMutableURLRequest {
let URL = NSURL(string: Router.baseURLString)!
let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
mutableURLRequest.HTTPMethod = method.rawValue
if let token = Router.OAuthToken {
mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
}
switch self {
case .GetActivities(let parameters):
return Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: parameters).0
}
}
}
Each time I load any view that has a tableview on it (say view2), the app re-fetches the data from the API. The tableview is part of a navigation controller and going to the view re-fetches the data but going back to the view does not.
Example:
- Case 1: view1 -> view2 = re-fetch JSON every time regardless
- Case 2: view2 -> view3 = load details of table cell that was tapped
- Case 3: view3 -> view2 = does not re-fetch JSON
- Case 4: view2 -> view1 = I am guessing view2 is no longer needed so it is dismissed
I would like that going from view1 -> view2 does not need to re-fetch the data each time if it has it in cache and the only way to refresh is either after the user logs back in to the app or using the pull to refresh feature.
I am new to Swift development so any guidance on how to cache JSON using either Alamofire or Haneke is greatly appreciated.
Haneke looks promising but I am not sure how to implement it using Alamofires post parameters.
Many thanks.
Source: (StackOverflow)
I am trying to integration with AWS SDK but the image is not showing up.
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCollectionViewCell", forIndexPath: indexPath) as! MyCollectionViewCell
let downloadURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent("myImage.jpg")
let downloadRequest = AWSS3TransferManagerDownloadRequest()
downloadRequest.bucket = "stg"
downloadRequest.key = "myImage.jpg"
downloadRequest.downloadingFileURL = downloadURL
let transferManager = AWSS3TransferManager.defaultS3TransferManager()
transferManager.download(downloadRequest).continueWithBlock { (task) -> AnyObject! in
if task.error != nil {
print("Failed to download S3 with error \(task.error)")
}
if task.result != nil {
//let output = task.result as! AWSS3TransferManagerDownloadOutput
cell.imageView.contentMode = UIViewContentMode.ScaleAspectFit
cell.imageView?.hnk_setImageFromURL(downloadURL)
}
return nil
}
return cell
}
Please advice. Thank you.
Source: (StackOverflow)