GithubHelp home page GithubHelp logo

spotify / sptpersistentcache Goto Github PK

View Code? Open in Web Editor NEW
1.2K 57.0 83.0 3.85 MB

Everyone tries to implement a cache at some point in their iOS app’s lifecycle, and this is ours.

License: Apache License 2.0

Ruby 0.34% Objective-C 95.77% C 1.85% Shell 2.04%

sptpersistentcache's Introduction

SPTPersistentCache

Coverage Status Documentation License CocoaPods Carthage compatible Spotify FOSS Slack Readme Score

Everyone tries to implement a cache at some point in their app’s lifecycle, and this is ours. This is a library that allows people to cache NSData with time to live (TTL) values and semantics for disk management.

  • 📱 iOS 8.0+
  • 💻 OS X 10.10+

Architecture 📐

SPTPersistentCache is designed as an LRU cache which makes use of the file system to store files as well as inserting a cache header into each file. This cache header allows us to track the TTL, last updated time, the redundancy check and more. This allows the cache to know how often a file is accessed, when it was made, whether it has become corrupt and allows decisions to be made on whether the cache is stale.

The use of different files rather than a single binary file allows multiple reads/writes on different files within the cache without complicated blocking logic. The cache header in each file can be removed quite easily, this can be seen in the SPTPersistentCacheViewer tool that is made to run on OS X.

Included here is also the ability to schedule garbage collection over the cache, which allows the user to ensure they are never using too much space for commonly cache data (such as images).

Installation 📥

SPTPersistentCache can be installed in a variety of ways including traditional static libraries and dynamic frameworks.

Static Library

Simply include SPTPersistentCache.xcodeproj in your App’s Xcode project, and link your app with the library in the “Build Phases” section.

CocoaPods

We are indexed on CocoaPods, which can be installed using Ruby gems:

$ gem install cocoapods

Then simply add SPTPersistentCache to your Podfile.

pod 'SPTPersistentCache', '~> 1.1.1'

Lastly let CocoaPods do its thing by running:

$ pod install

Carthage

We support Carthage and provide pre-built binary frameworks for all new releases. Start by making sure you have the latest version of Carthage installed, e.g. using Homebrew:

$ brew update
$ brew install carthage

You will also need to add SPTPersistentCache to your Cartfile:

github "spotify/SPTPersistentCache" ~> 1.1.1

After that is all said and done, let Carthage pull in SPTPersistentCache like so:

$ carthage update

Next up, you need to add the framework to the Xcode project of your App. Lastly link the framework with your App and copy it to the App’s Frameworks directory under the “Build Phases”.

Usage example 👀

For an example of this framework's usage, see the demo application SPTPersistentCacheDemo in SPTPersistentCache.xcworkspace.

Creating the SPTPersistentCache

It is best to use different caches for different types of data you want to store, and not just one big cache for your entire application. However, only create one SPTPersistentCache instance for each cache, otherwise you might encounter anomalies when the two different caches end up writing to the same file.

NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:@"com.spotify.demo.image.cache"];

SPTPersistentCacheOptions *options = [SPTPersistentCacheOptions new];
options.cachePath = cachePath;
options.cacheIdentifier = @"com.spotify.demo.image.cache";
options.defaultExpirationPeriod = 60 * 60 * 24 * 30; // 30 days
options.garbageCollectionInterval = (NSUInteger)(1.5 * SPTPersistentCacheDefaultGCIntervalSec);
options.sizeConstraintBytes = 1024 * 1024 * 10; // 10 MiB
options.debugOutput = ^(NSString *string) {
    NSLog(@"%@", string);
};

SPTPersistentCache *cache = [[SPTPersistentCache alloc] initWithOptions:options];

Storing Data in the SPTPersistentCache

When storing data in the SPTPersistentCache, you must be aware of the file system semantics. The key will be used as the file name within the cache directory to save. The reason we did not implement a hash function under the hood is because we wanted to give the option of what hash function to use to the user, so it is recommended that when you insert data into the cache for a key, that you create the key using your own hashing function (at Spotify we use SHA1, although better hashing functions exist these days). If you want the cache record, i.e. file, to exist without any TTL make sure you store it as a locked file.

NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"my-image"]);
NSString *key = @"MyHashValue";
[self.cache storeData:data
              forKey:key
              locked:YES
        withCallback:^(SPTPersistentCacheResponse *cacheResponse) {
             NSLog(@"cacheResponse = %@", cacheResponse);
        } onQueue:dispatch_get_main_queue()];

Loading Data in the SPTPersistentCache

In order to restore data you already have saved in the SPTPersistentCache, you simply feed it the same key that you used to store the data.

NSString *key = @"MyHashValue";
[self.cache loadDataForKey:key withCallback:^(SPTPersistentCacheResponse *cacheResponse) {
    UIImage *image = [UIImage imageWithData:cacheResponse.record.data];
} onQueue:dispatch_get_main_queue()];

Note that if the TTL has expired, you will not receive a result.

Locking/Unlocking files

Sometimes you may want to lock a file in SPTPersistentCache long after it has been expired by its TTL. An example of where we do this at Spotify is images relating to the cover art of the songs you have offlined (we wouldn't want to invalidate these images when you are away on vacation). When you have locked a file, you must make sure you unlock it eventually, otherwise it will stay around forever. A lock is basically a contract between the cache and it's consumer that the data will remain in the cache until it is explicitly unlocked.

NSString *key = @"MyHashValue";
[self.cache lockDataForKeys:@[key] callback:nil queue:nil];
// Now my data is safe within the arms of the cache
[self.cache unlockDataForKeys:@[key] callback:nil queue:nil];
// Now my data will be subject to its original TTL

Note: That if you exceed the constrained size in your cache, even locked files can be subject to pruning.

Using the garbage collector

The garbage collection functionality in SPTPersistentCache is not automatically run, you have to call it manually using scheduleGarbageCollector.

[self.cache scheduleGarbageCollection];

This will schedule garbage collection on the interval you supplied in the SPTPersistentCacheOptions class, by default this is the SPTPersistentCacheDefaultExpirationTimeSec external variable. To unschedule the garbage collector simply call the opposite function unscheduleGarbageCollector.

[self.cache unscheduleGarbageCollection];

Manually managing cache usage

There are times when you may want to pre-empty a garbage collection that is scheduled, wipe the cache or simply remove all locked/unlocked files indiscriminantly. To support these cases we have provided methods to do just this.

// Lets wipe all the files we haven't explicitly locked
[self.cache wipeUnlockedFiles];
NSLog(@"Size = %@", @(self.cache.totalUsedSizeInBytes));
// Now let's wipe all the files we have explicitly locked
[self.cache wipeLockedFiles];
NSLog(@"Size = %@", @(self.cache.totalUsedSizeInBytes));
// Why not just wipe the entire cache?
[self.cache prune];
NSLog(@"Size = %@", @(self.cache.totalUsedSizeInBytes));

Background story 📖

At Spotify we began to standardise the way we handled images in a centralised way, and in doing so we initially created a component that was handling images and their caching. But then our requirements changed, and we began to need caching for our backend calls and preview MP3 downloads as well. In doing so, we managed to separate out our caching logic into a generic component that can be used for any piece of data.

Thus we boiled down what we needed in a cache, the key features being TTL on specific pieces of data, disk management to make sure we don't use too much, and protections against data corruption. It also became very useful to separate different caches into separate files (such as images and mp3s), in order to easily measure how much space each item is taking up.

Tools 🔨

Having a nice GUI tool to inspect the contents of an SPTPersistentCache directory would be nice, so we made one. In this repository we have a project called SPTPersistentCacheViewer.xcodeproj which is part of the SPTPersistentCache.xcworkspace. When you open it and build it for OS X, you will see a GUI that allows you to inspect the contents of a cache, including individual items TTL and payload size.

SPTPersistentCacheViewer

Contributing 📬

Contributions are welcomed, have a look at the CONTRIBUTING.md document for more information.

License 📝

The project is available under the Apache 2.0 license.

Acknowledgements

sptpersistentcache's People

Contributors

8w9ag avatar aleksandergrzyb avatar ceciliahumlelu avatar chocochipset avatar chrisbtreats avatar dflems avatar hallski avatar jensayton avatar jesjos avatar kmcbride avatar neonichu avatar rastersize avatar szymonmrozek avatar themackworth avatar vtourraine avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sptpersistentcache's Issues

Deployment target triggers a compiler warning in Xcode 12+

Xcode 12 dropped support for iOS 8:
https://developer.apple.com/documentation/xcode-release-notes/xcode-12-release-notes

When compiling the project in Xcode for the simulator I get the following warning:

The iOS Simulator deployment target 'IPHONEOS_DEPLOYMENT_TARGET' is set to 8.0, but the range of supported deployment target versions is 9.0 to 14.0.99.

I can see that from the xcconfig file that deployment target is explicitly set to 8.0:
https://github.com/spotify/SPTPersistentCache/blob/master/ci/spotify_os.xcconfig#L21

I've increased to 12.0 locally for my project and it all builds ok. However I do not want to deviate the fork from the Spotify repo.

Would it be possible to bump to 9.0 at least please?

Doesn't compile under Xcode 10

@8W9aG Thank you in advance for taking a look at this.

SPTPersistentCache doesn't compile via standard Carthage pull under Xcode 10.

The error is:

CompileC /Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/Objects-normal/armv7/SPTPersistentCache.o /Users/z002r44/Dustin-Harmony-iOS/Carthage/Checkouts/SPTPersistentCache/Sources/SPTPersistentCache.m normal armv7 objective-c com.apple.compilers.llvm.clang.1_0.compiler (in target: SPTPersistentCache-iOS)
    cd /Users/z002r44/Dustin-Harmony-iOS/Carthage/Checkouts/SPTPersistentCache/SPTPersistentCacheFramework
    export LANG=en_US.US-ASCII
    /Users/z002r44/Downloads/Xcode10.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c -arch armv7 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu11 -fobjc-arc -fmodules -gmodules -fmodules-cache-path=/Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/ModuleCache.noindex -fno-autolink -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -fbuild-session-file=/Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/ModuleCache.noindex/Session.modulevalidation -fmodules-validate-once-per-build-session -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -fmodule-name=SPTPersistentCache -Wno-trigraphs -fpascal-strings -Os -fno-common -Werror=incompatible-pointer-types -Werror=implicit-function-declaration -Wmissing-field-initializers -Wmissing-prototypes -Werror=return-type -Wdocumentation -Wunreachable-code -Wnullable-to-nonnull-conversion -Wimplicit-atomic-properties -Werror=deprecated-objc-isa-usage -Wno-objc-interface-ivars -Werror=objc-root-class -Warc-repeated-use-of-weak -Wno-arc-maybe-repeated-use-of-weak -Wexplicit-ownership-type -Wimplicit-retain-self -Wduplicate-method-match -Wmissing-braces -Wparentheses -Wswitch -Wunused-function -Wunused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wconditional-uninitialized -Wunknown-pragmas -Wshadow -Wfour-char-constants -Wconversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wfloat-conversion -Wnon-literal-null-conversion -Wobjc-literal-conversion -Wassign-enum -Wsign-compare -Wshorten-64-to-32 -Wpointer-sign -Wnewline-eof -Wselector -Wstrict-selector-match -Wundeclared-selector -Wdeprecated-implementations -DNS_BLOCK_ASSERTIONS=1 -DOBJC_OLD_DISPATCH_PROTOTYPES=0 -isysroot /Users/z002r44/Downloads/Xcode10.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.0.sdk -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -miphoneos-version-min=8.0 -g -Wsign-conversion -Winfinite-recursion -Wcomma -Wblock-capture-autoreleasing -Wstrict-prototypes -Wno-semicolon-before-method-body -fembed-bitcode -iquote /Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/SPTPersistentCache-generated-files.hmap -I/Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/SPTPersistentCache-own-target-headers.hmap -I/Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/SPTPersistentCache-all-non-framework-target-headers.hmap -ivfsoverlay /Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/all-product-headers.yaml -iquote /Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/SPTPersistentCache-project-headers.hmap -I/Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/BuildProductsPath/Release-iphoneos/include -I../include -I/Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/DerivedSources/armv7 -I/Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/DerivedSources -Weverything -Wno-error=deprecated -Wno-objc-missing-property-synthesis -Wno-gnu-conditional-omitted-operand -Wno-gnu -Wno-documentation-unknown-command -Wno-reserved-id-macro -Wno-auto-import -Wno-missing-variable-declarations -Wno-c++98-compat -Werror -Wno-direct-ivar-access -Wno-padded -F/Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/BuildProductsPath/Release-iphoneos -MMD -MT dependencies -MF /Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/Objects-normal/armv7/SPTPersistentCache.d --serialize-diagnostics /Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/Objects-normal/armv7/SPTPersistentCache.dia -c /Users/z002r44/Dustin-Harmony-iOS/Carthage/Checkouts/SPTPersistentCache/Sources/SPTPersistentCache.m -o /Users/z002r44/Library/Caches/org.carthage.CarthageKit/DerivedData/10.0_10A254a/SPTPersistentCache/1.1.1/Build/Intermediates.noindex/ArchiveIntermediates/SPTPersistentCache-iOS/IntermediateBuildFilesPath/SPTPersistentCacheFramework.build/Release-iphoneos/SPTPersistentCache-iOS.build/Objects-normal/armv7/SPTPersistentCache.o
/Users/z002r44/Dustin-Harmony-iOS/Carthage/Checkouts/SPTPersistentCache/Sources/SPTPersistentCache.m:737:80: error: implicit conversion from nullable pointer 'NSString * _Nullable' to non-nullable pointer type 'ObjectType _Nonnull' (aka 'id') [-Werror,-Wnullable-to-nonnull-conversion]
                                        userInfo:@{ NSLocalizedDescriptionKey: @(errorString) }];
                                                                               ^
/Users/z002r44/Dustin-Harmony-iOS/Carthage/Checkouts/SPTPersistentCache/Sources/SPTPersistentCache.m:965:30: warning: messaging unqualified id [-Wobjc-messaging-id]
        currentCacheSize += [image[SPTDataCacheFileAttributesKey][NSFileSize] integerValue];
                             ^
/Users/z002r44/Dustin-Harmony-iOS/Carthage/Checkouts/SPTPersistentCache/Sources/SPTPersistentCache.m:984:30: warning: messaging unqualified id [-Wobjc-messaging-id]
        currentCacheSize -= [image[SPTDataCacheFileAttributesKey][NSFileSize] integerValue];

I put in a PR to fix, but can't figure out why the CI process fails on the PR.
Would like to use SPTPersistentCache from master if possible, not from a fork that I took:
https://github.com/DanEdgarTarget/SPTPersistentCache

Thank you for any help.

currentTimeCallback, do we need it?

Just wondering if we really need the currentTimeCallback parameter in SPTPersistentCacheOptions.

It makes the API more complex and I'm not sure if it's a common to require something different than the default implementation we provide.

@spotify/objc-dev

Initializing cache results in EXC_BAD_INSTRUCTION

By using the example of the readme I am trying to initialize the cache in my AppDelegate.m. Without doing anything further with it I am getting a EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) Exception in Thread 1.
With the find Zombie Objects setting i get the following terminal output:

2018-03-01 12:54:35.476398+0100 VideoCaching[50180:944549] *** -[NSPathStore2 release]: message sent to deallocated instance 0x7f8d6760e500

Wrong nullability flags on SPTPersistentCacheResponse

The interface of SPTPersistentCacheResponse tells the compiler that all its properties are NONNULL but it's obvious that it's not true, you cannot have result and error instantiated at the same time.

This is a big issue in Swift3 projects, because if you check directly the presence of record without checking result before, the app will crash at runtime, because the compiler cannot let you use optional access to these properties.

A corrected version of it could be

@interface SPTPersistentCacheResponse : NSObject

/**
 * @see SPTPersistentCacheResponseCode
 */
@property (nonatomic, assign, readonly) SPTPersistentCacheResponseCode result;
/**
 * Defines error of response if appliable
 */
@property (nonatomic, strong, readonly, nullable) NSError *error;
/**
 * @see SPTPersistentCacheRecord
 */
@property (nonatomic, strong, readonly, nullable) SPTPersistentCacheRecord *record;

@end

Need a new version?

There are a lot of commits after releasing 1.0. So should this project release a new version up to date ?

Retrieved UIImage has wrong size dimensions

I am creating a UIImage from the MapKit Snapshot. The image is fine, until I retrieve it from the cache, at which point, the image is doubled in size. I have tried converting to both PNG format, and JPEG format, with the same results for both.

The only thing I can think of is that it may have to do with the scale, when returning the image from cache

Can't access cache by sync methods

I expect to get the cache from the return value rather than in a block
Is there an alternative way to implement that makes it can return cache value directly?

- (BOOL)loadDataForKey:(NSString *)key
          withCallback:(SPTPersistentCacheResponseCallback _Nullable)callback
               onQueue:(dispatch_queue_t _Nullable)queue;

Need help about caching

I have an app, that is a comic book reader, so the user can download a book then read it later, even without internet.

I'm thinking to cache all pages(images) of the book with SPTPersistentCache.
I need to save each book in a different folder, ex: spider man will be saved on a folder spider-man/pages, minions will be saved on minions/pages and so on...

Also SPTPersistentCache can't garbage the books downloaded, it must keep the cache until the user delete that specific book. Also no disk size limite.

What I need is the very same way Spotify does with offline musics downloaded. Can I do that?

How to get URI of cached images?

I see in the code that there are functions to determine the URI of the cached images, however, they are not exposed. Are there any exposed functions, or recommended methods for determining the URI of a cached image? I need this for an application that will be using QMChatViewController, and the library only accepts URI paths for image attachments.

Thanks!

Change the default cache path

We should change the default cache location the next time we release a breaking update. I think the earliest we can do that is with version 2.0 (which is a far ways off, not even planned).

Currently the path used is the temporary directory appended with a path component that is very specific.

[NSTemporaryDirectory() stringByAppendingPathComponent:@"/com.spotify.temppersistent.image.cache"];

(SPTPersistentCacheOptions.m#L51)

It would be better to set it to a more generically named path, such as:

[NSTemporaryDirectory() stringByAppendingPathComponent:@"/com.spotify.persistentcache.default"];

Cache fails to store large files

Whenever we try to save large files (>100MB, actual size depends on device capabilities) to cache, nothing happens except console log message like

*** mach_vm_map(size=997462016) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug

The problem is in SPTPersistentCache method

- (NSError *)storeDataSync:(NSData *)data
                    forKey:(NSString *)key
                       ttl:(NSUInteger)ttl
                    locked:(BOOL)isLocked
              withCallback:(SPTPersistentCacheResponseCallback)callback
                   onQueue:(dispatch_queue_t)queue

The following code does not work for large rawDataLength
NSMutableData *rawData = [NSMutableData dataWithCapacity:rawDataLength];

One way to handle large amounts of data is to fill temporary file with relatively small blocks of data first and then writing it atomically to target filePath

Scheduling of garbage collection

I'm considering how to schedule the garbage collector for an app that does not have long sessions. I understand that the current way of scheduling works fine for Spotify, since your app will be long running in the background.

Do you guys have any suggestions on how to handle scheduling in an app where the average user session is around 20 seconds? Scheduling it to run every 10 seconds seems unnecessary, but scheduling it to run at > 20 seconds could mean that the GC never runs for some users (since we need to unschedule when the app enters the background, to avoid an NSTimer keeping the app awake).

I think ideally, SPTPersistentCache should have a way to manually start the GC instead of scheduling it. This would allow us to run it once when the app enters background before it gets terminated.

I could achieve this in the current way by scheduling it at 0 seconds when the app enters background, and then immediately unscheduling it. This seems kind of insecure though, since it could run 10 times or even cancel before it runs at all.

Any input is appreciated!

Framework Fails to Build

When embedding the SPTPersistentCacheFramework Xcode project in your Xcode project as a dependency, the project fails to build in file SPTPersistentCache.h

'SPTPersistentCache/SPTPersistentCacheImplementation.h' file not found

It doesn't seem like this file was added to SPTPersistentCacheFramework.xcodeproj

"Messaging unqualified id" error in Xcode 11b1

Buildng the app with Xcode 11b1 results in 3 of the following errors:

Messaging unqualified id

in:

SPTPersistentCacheOptions.mL111
SPTPersistentCache.mL967
SPTPersistentCache.mL986

I admit I am a bit miffed on what the actual problem is. Despite a few years of exclusive Swift development, I feel like I should be able to infer what it doesn't like about the object being messaged in these 3 cases.

In the first, init is triggering the warning.
In the second two, integerValue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.