Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Calculate cache size methed #44

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions AwesomeCache.podspec
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
Pod::Spec.new do |s|
s.name = "AwesomeCache"
s.name = "AwesomeCache-hwh"
s.version = "2.0"
s.summary = "Delightful on-disk cache (written in Swift)"
s.description = "Delightful on-disk cache (written in Swift). Backed by NSCache for maximum performance and support for expiry of single objects."
s.homepage = "https://github.com/aschuch/AwesomeCache"
s.summary = "轻量级本地缓存swift 库"
s.description = "轻量级本地缓存swift 库. Backed by NSCache for maximum performance and support for expiry of single objects."
s.homepage = "https://github.com/huang1988519/"
s.license = { :type => "MIT", :file => "LICENSE" }
s.author = { "Alexander Schuch" => "[email protected]" }
s.social_media_url = "http://twitter.com/schuchalexander"
s.author = { "huangwh" => "[email protected]" }
s.social_media_url = "http://huang1988519.github.io/"
s.platform = :ios
s.ios.deployment_target = "8.0"
s.source = { :git => "https://github.com/aschuch/AwesomeCache.git", :tag => s.version }
s.source = { :git => "https://github.com/huang1988519/AwesomeCache.git", :tag => s.version }
s.requires_arc = true
s.source_files = "AwesomeCache/Cache.swift", "AwesomeCache/CacheObject.swift"
end
46 changes: 44 additions & 2 deletions AwesomeCache/Cache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,48 @@ public class Cache<T: NSCoding> {
}
}
}

//MARK: -- Calculate Disk Cache Size
/**
Calculate disk cache size

- parameter completionHandler: Calculate complete then callback
*/
public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())?) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
let diskCacheURL = self.cacheDirectory

let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey]
var diskCacheSize: UInt = 0

if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil),
urls = fileEnumerator.allObjects as? [NSURL] {
for fileURL in urls {
do {
let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys)
// If it is a Directory. Continue to next file URL.
if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue {
if isDirectory {
continue
}
}

if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize += fileSize.unsignedLongValue
}
} catch _ {
}

}
}

dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let completionHandler = completionHandler {
completionHandler(size: diskCacheSize)
}
})
})
}


// MARK: Subscripting

Expand Down Expand Up @@ -259,5 +300,6 @@ public class Cache<T: NSCoding> {
return date
}
}



}
5 changes: 3 additions & 2 deletions Example/Base.lproj/LaunchScreen.xib
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="6245" systemVersion="13E28" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="3.0" toolsVersion="9531" systemVersion="15C50" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6238"/>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>
</dependencies>
<objects>
<placeholder placeholderIdentifier="IBFilesOwner" id="-1" userLabel="File's Owner"/>
Expand Down
26 changes: 22 additions & 4 deletions Example/Base.lproj/Main.storyboard
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="6751" systemVersion="14C1514" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="vXZ-lx-hvc">
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="9531" systemVersion="15C50" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="vXZ-lx-hvc">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="6736"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="9529"/>
<capability name="Constraints to layout margins" minToolsVersion="6.0"/>
</dependencies>
<scenes>
Expand All @@ -29,7 +29,7 @@
<textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
</textView>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="WO3-lW-cdC">
<rect key="frame" x="232" y="176" width="137" height="30"/>
<rect key="frame" x="233.5" y="176" width="134" height="30"/>
<state key="normal" title="Reload From Cache">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
Expand All @@ -38,24 +38,42 @@
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="cUO-c3-goo">
<rect key="frame" x="251" y="214" width="99" height="30"/>
<rect key="frame" x="252" y="214" width="97" height="30"/>
<state key="normal" title="Save in Cache">
<color key="titleShadowColor" white="0.5" alpha="1" colorSpace="calibratedWhite"/>
</state>
<connections>
<action selector="saveInCache:" destination="vXZ-lx-hvc" eventType="touchUpInside" id="STv-qo-lMe"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="2zZ-Oa-gMA">
<rect key="frame" x="244" y="252" width="112" height="30"/>
<state key="normal" title="Calculate Cache"/>
<connections>
<action selector="calculateCacheSize:" destination="vXZ-lx-hvc" eventType="touchUpInside" id="5oh-5C-tQX"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="AhF-JF-WWW">
<rect key="frame" x="249" y="285" width="103" height="30"/>
<state key="normal" title="Remove Cache"/>
<connections>
<action selector="removeCache:" destination="vXZ-lx-hvc" eventType="touchUpInside" id="PrC-4c-isf"/>
</connections>
</button>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<constraints>
<constraint firstAttribute="centerX" secondItem="cUO-c3-goo" secondAttribute="centerX" constant="-0.5" id="0s9-IX-nOm"/>
<constraint firstAttribute="width" secondItem="eud-Cw-V1B" secondAttribute="width" constant="20" id="1xR-At-DgT"/>
<constraint firstItem="AhF-JF-WWW" firstAttribute="top" secondItem="2zZ-Oa-gMA" secondAttribute="bottom" constant="3" id="ABg-DY-nLW"/>
<constraint firstItem="eud-Cw-V1B" firstAttribute="top" secondItem="jyV-Pf-zRb" secondAttribute="bottom" constant="187" id="I4t-hI-sMB"/>
<constraint firstItem="2zZ-Oa-gMA" firstAttribute="centerX" secondItem="cUO-c3-goo" secondAttribute="centerX" id="I6D-7W-dvh"/>
<constraint firstItem="2zZ-Oa-gMA" firstAttribute="top" secondItem="cUO-c3-goo" secondAttribute="bottom" constant="8" id="LkJ-d5-au6"/>
<constraint firstAttribute="centerX" secondItem="WO3-lW-cdC" secondAttribute="centerX" constant="-0.5" id="Nsq-S3-MP5"/>
<constraint firstItem="WO3-lW-cdC" firstAttribute="top" secondItem="eud-Cw-V1B" secondAttribute="bottom" constant="8" id="Uvq-XJ-UMa"/>
<constraint firstItem="eud-Cw-V1B" firstAttribute="centerX" secondItem="WO3-lW-cdC" secondAttribute="centerX" id="VcU-lq-hkO"/>
<constraint firstItem="eud-Cw-V1B" firstAttribute="top" secondItem="jyV-Pf-zRb" secondAttribute="bottom" id="jx7-Jr-pHE"/>
<constraint firstItem="AhF-JF-WWW" firstAttribute="centerX" secondItem="2zZ-Oa-gMA" secondAttribute="centerX" id="l3S-AG-GRi"/>
<constraint firstAttribute="centerX" secondItem="eud-Cw-V1B" secondAttribute="centerX" constant="-0.5" id="m6C-XT-ZOp"/>
<constraint firstAttribute="centerY" secondItem="eud-Cw-V1B" secondAttribute="centerY" constant="19" id="wIl-qR-x81"/>
<constraint firstItem="WO3-lW-cdC" firstAttribute="top" secondItem="eud-Cw-V1B" secondAttribute="bottom" constant="8" symbolic="YES" id="xsN-t4-xFi"/>
Expand Down
9 changes: 9 additions & 0 deletions Example/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,14 @@ class ViewController: UIViewController {
@IBAction func saveInCache(sender: AnyObject?) {
cache["myText"] = textView.text
}
@IBAction func calculateCacheSize(sender: AnyObject?) {
cache.calculateDiskCacheSizeWithCompletionHandler { (size) -> () in
let kSize = String(format: "%d", size)
print(kSize)
}
}
@IBAction func removeCache(sender: AnyObject) {
cache.removeAllObjects()
}
}

10 changes: 9 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,19 @@ cache.setObject("Alex", forKey: "name", expires: .Date(NSDate(timeIntervalSince1
If an object is accessed after its expiry date, it is automatically removed from the cache and deleted from disk.
However, you are responsible to delete expired objects regularly by calling `removeExpiredObjects` (e.g. on app launch).

### Calculate cache size
Asynchronous calculate cache size , callback size on main thread.
```swift
cache.calculateDiskCacheSizeWithCompletionHandler { (size) -> () in
let kSize = String(format: "%d", size)
print(kSize)
}
```

### Awesome API Caching

API responses are usually cached for a specific period of time. AwesomeCache provides an easy method to cache a block of asynchronous tasks.

```swift
cache.setObjectForKey("name", cacheBlock: { success, failure in
// Perform tasks, e.g. call an API
Expand Down