├── DEMO.png
├── LICENSE
├── README.md
├── XHNetworkCacheSwift.podspec
├── XHNetworkCacheSwift
└── XHNetworkCache.swift
├── XHNetworkCacheSwiftExample.xcodeproj
├── project.pbxproj
├── project.xcworkspace
│ ├── contents.xcworkspacedata
│ └── xcuserdata
│ │ └── xiaohui.xcuserdatad
│ │ └── UserInterfaceState.xcuserstate
└── xcuserdata
│ └── xiaohui.xcuserdatad
│ └── xcschemes
│ ├── XHNetworkCacheSwiftExample.xcscheme
│ └── xcschememanagement.plist
└── XHNetworkCacheSwiftExample
├── AppDelegate.swift
├── Assets.xcassets
└── AppIcon.appiconset
│ └── Contents.json
├── Base.lproj
└── LaunchScreen.storyboard
├── Info.plist
├── ViewController.swift
├── ViewController.xib
└── XHNetworkCacheSwiftExample-Bridging-Header.h
/DEMO.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CoderZhuXH/XHNetworkCacheSwift/768ca4e2a1796a0cd1d05b5c7a9906e19ef4f2db/DEMO.png
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2016 XHNetworkCacheSwift (https://github.com/CoderZhuXH/XHNetworkCacheSwift)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # XHNetworkCacheSwift
2 | #### 一行代码将网络数据持久化
3 | #### OC版本请戳这里>>> https://github.com/CoderZhuXH/XHNetworkCache
4 | ###技术交流群(群号:537476189)
5 | ## 使用方法:
6 | ### 1.(同步)写入/更新
7 | ```objc
8 | //将数据(同步)写入磁盘缓存(参数1:服务器返回的JSON数据, 参数2:数据请求URL)
9 | //[按APP版本号缓存,不同版本APP,同一接口缓存数据互不干扰]
10 | if XHNetworkCache.saveJsonResponseToCacheFile(responseObject as AnyObject, URL: URLString)
11 | {
12 | print("(同步)保存/更新成功")
13 | }
14 | else
15 | {
16 | print("(同步)保存/更新失败")
17 | }
18 |
19 | ```
20 | ### 2.(异步)写入/更新
21 | ```objc
22 | //将数据(异步)写入磁盘缓存(参数1:服务器返回的JSON数据, 参数2:数据请求URL)
23 | //[按APP版本号缓存,不同版本APP,同一接口缓存数据互不干扰]
24 | XHNetworkCache.save_asyncJsonResponseToCacheFile(responseObject as AnyObject, URL: URLString) { (result) in
25 | if(result)
26 | {
27 | print("(异步)保存/更新成功")
28 | }
29 | else
30 | {
31 | print("(异步)保存/更新成功")
32 | }
33 | }
34 |
35 | ```
36 | ### 3.获取缓存数据
37 | ```objc
38 | //获取缓存数据(参数:请求URL,返回:JSON数据)
39 | if let json = XHNetworkCache.cacheJsonWithURL(URLString)
40 | {
41 | print(json)
42 | }
43 | ```
44 | ### 4.获取缓存路径
45 | ```objc
46 | //获取缓存路径
47 | let path = XHNetworkCache.cachePath()
48 |
49 | ```
50 | ### 5.清除缓存
51 | ```objc
52 | //清除缓存
53 | if XHNetworkCache.clearCache()
54 | {
55 | print("清除缓存成功")
56 | }
57 | else
58 | {
59 | print("清除缓存失败")
60 | }
61 | ```
62 |
63 | ### 6.获取缓存总大小(M)
64 | ```objc
65 | //获取缓存总大小(M)
66 | let size = XHNetworkCache.cacheSize()
67 | ```
68 | ## 安装
69 | ### 手动添加:
70 | * 1.将 XHNetworkCacheSwift 文件夹添加到工程目录中
71 | * 2.在项目`Bridging-Header.h` 桥接文件中 `#import`
72 | * 3.`Bridging-Header.h`桥接文件怎么创建??? 请自行Google或百度
73 |
74 | ## 系统要求
75 | * 该项目最低支持 iOS 8.0 和 Xcode 8.0
76 |
77 | ## 许可证
78 | XHNetworkCacheSwift 使用 MIT 许可证,详情见 LICENSE 文件
--------------------------------------------------------------------------------
/XHNetworkCacheSwift.podspec:
--------------------------------------------------------------------------------
1 | Pod::Spec.new do |s|
2 | s.name = "XHNetworkCacheSwift"
3 | s.version = "1.0.0"
4 | s.summary = "swift,一行代码将网络数据持久化"
5 | s.homepage = "https://github.com/CoderZhuXH/XHNetworkCacheSwift"
6 | s.license = { :type => "MIT", :file => "LICENSE" }
7 | s.authors = { "Zhu Xiaohui" => "977950862@qq.com"}
8 | s.platform = :ios, "8.0"
9 | s.source = { :git => "https://github.com/CoderZhuXH/XHNetworkCacheSwift.git", :tag => s.version }
10 | s.source_files = "XHNetworkCacheSwift", "*.{swift}"
11 | s.requires_arc = true
12 |
13 | end
14 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwift/XHNetworkCache.swift:
--------------------------------------------------------------------------------
1 | //
2 | // XHNetworkCache.swift
3 | // XHNetworkCacheSwiftExample
4 | //
5 | // Created by xiaohui on 16/8/12.
6 | // Copyright © 2016年 CoderZhuXH. All rights reserved.
7 | // 代码地址:https://github.com/CoderZhuXH/XHNetworkCacheSwift
8 |
9 | /**
10 | * 注意: 使用前请在'-Bridging-Header.h' 桥接文件中导入 #import
11 | */
12 |
13 | import UIKit
14 |
15 | extension XHNetworkCache
16 | {
17 | /**
18 | 写入/更新缓存(同步) [按APP版本号缓存,不同版本APP,同一接口缓存数据互不干扰]
19 |
20 | - parameter jsonResponse: 要写入的数据(JSON)
21 | - parameter URL: 数据请求URL
22 |
23 | - returns: 是否写入成功
24 | */
25 | public class func saveJsonResponseToCacheFile(_ jsonResponse: AnyObject,URL: String) -> Bool {
26 |
27 | let data = jsonToData(jsonResponse)
28 | return FileManager.default.createFile(atPath: cacheFilePathWithURL(URL), contents: data, attributes: nil)
29 |
30 | }
31 |
32 | /**
33 | 写入/更新缓存(异步) [按APP版本号缓存,不同版本APP,同一接口缓存数据互不干扰]
34 |
35 | - parameter jsonResponse: 要写入的数据(JSON)
36 | - parameter URL: 数据请求URL
37 | - parameter completed: 异步完成回调(主线程回调)
38 | */
39 | public class func save_asyncJsonResponseToCacheFile(_ jsonResponse: AnyObject,URL: String, completed:@escaping (Bool) -> ()) {
40 |
41 | DispatchQueue.global().async{
42 |
43 | let result = saveJsonResponseToCacheFile(jsonResponse, URL: URL)
44 |
45 | DispatchQueue.main.async(execute: {
46 |
47 | completed(result)
48 | })
49 | }
50 | }
51 |
52 | /**
53 | 获取缓存的对象(同步)
54 |
55 | - parameter URL: 数据请求URL
56 |
57 | - returns: 缓存对象
58 | */
59 | public class func cacheJsonWithURL(_ URL: String) -> AnyObject? {
60 | let path: String = self.cacheFilePathWithURL(URL)
61 | let fileManager: FileManager = FileManager.default
62 | if fileManager.fileExists(atPath: path, isDirectory: nil) == true {
63 | let data: Data = fileManager.contents(atPath: path)!
64 | return self.dataToJson(data)
65 | }
66 |
67 | return nil
68 | }
69 |
70 | /**
71 | 获取缓存路径
72 |
73 | - returns: 缓存路径
74 | */
75 | public class func cachePath() -> String {
76 |
77 | let pathOfLibrary = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
78 | let path = pathOfLibrary.appendingPathComponent("XHNetworkCache")
79 | return path
80 | }
81 |
82 | /**
83 | 清除缓存
84 | */
85 | public class func clearCache() -> Bool{
86 | let fileManager: FileManager = FileManager.default
87 | let path: String = self.cachePath()
88 | do
89 | {
90 | try fileManager.removeItem(atPath: path)
91 | self.checkDirectory(self.cachePath())
92 | return true
93 | }
94 | catch let error as NSError
95 | {
96 | print("clearCache failed , error = \(error)")
97 | return false
98 | }
99 | }
100 |
101 | /**
102 | 获取缓存大小
103 |
104 | - returns: 缓存大小(单位:M)
105 | */
106 | public class func cacheSize()-> Float {
107 |
108 | let cachePath = self.cachePath()
109 | do
110 | {
111 | let fileArr = try FileManager.default.contentsOfDirectory(atPath: cachePath)
112 | var size:Float = 0
113 | for file in fileArr{
114 | let path = cachePath + "/\(file)"
115 | let floder = try! FileManager.default.attributesOfItem(atPath: path)
116 | for (abc, bcd) in floder {
117 | if abc == FileAttributeKey.size {
118 | size += (bcd as AnyObject).floatValue
119 | }
120 | }
121 | }
122 | let total = size / 1024.0 / 1024.0
123 | return total
124 | }
125 | catch
126 | {
127 | return 0;
128 | }
129 | }
130 |
131 | }
132 |
133 | open class XHNetworkCache {
134 |
135 | //MARK: - private
136 | fileprivate class func jsonToData(_ jsonResponse: AnyObject) -> Data? {
137 |
138 | do{
139 |
140 | let data = try JSONSerialization.data(withJSONObject: jsonResponse, options: JSONSerialization.WritingOptions.prettyPrinted)
141 | return data;
142 |
143 | }catch
144 | {
145 | return nil
146 | }
147 | }
148 |
149 | fileprivate class func dataToJson(_ data: Data) -> AnyObject? {
150 |
151 | do{
152 |
153 | let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
154 | return json as AnyObject?
155 |
156 | }
157 | catch
158 | {
159 | return nil
160 | }
161 | }
162 |
163 | fileprivate class func cacheFilePathWithURL(_ URL: String) -> String {
164 | var path: String = self.cachePath()
165 | self.checkDirectory(path)
166 | //check路径
167 | let cacheFileNameString: String = "URL:\(URL) AppVersion:\(self.appVersionString())"
168 | let cacheFileName: String = self.md5StringFromString(cacheFileNameString)
169 | path = path + "/" + cacheFileName
170 | return path
171 | }
172 |
173 | fileprivate class func checkDirectory(_ path: String) {
174 | let fileManager: FileManager = FileManager.default
175 |
176 | var isDir = ObjCBool(false) //isDir判断是否为文件夹
177 |
178 | fileManager.fileExists(atPath: path, isDirectory: &isDir)
179 |
180 | if !fileManager.fileExists(atPath: path, isDirectory: &isDir) {
181 |
182 | self.createBaseDirectoryAtPath(path)
183 |
184 | } else {
185 |
186 | if !isDir.boolValue {
187 |
188 | do
189 | {
190 | try fileManager.removeItem(atPath: path)
191 | self.createBaseDirectoryAtPath(path)
192 | }
193 | catch let error as NSError
194 | {
195 | print("create cache directory failed, error = %@", error)
196 |
197 | }
198 | }
199 | }
200 | }
201 |
202 | fileprivate class func createBaseDirectoryAtPath(_ path: String) {
203 |
204 | do
205 | {
206 | try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: true, attributes: nil)
207 | print("path ="+path)
208 | self.addDoNotBackupAttribute(path)
209 | }
210 | catch let error as NSError
211 | {
212 | print("create cache directory failed, error = %@", error)
213 |
214 | }
215 | }
216 |
217 | fileprivate class func addDoNotBackupAttribute(_ path: String) {
218 | let url: URL = URL(fileURLWithPath: path)
219 |
220 | do
221 | {
222 | try (url as NSURL).setResourceValue(NSNumber(value: true as Bool), forKey: URLResourceKey.isExcludedFromBackupKey)
223 | }
224 | catch let error as NSError
225 | {
226 | print("error to set do not backup attribute, error = %@", error)
227 |
228 | }
229 | }
230 |
231 | fileprivate class func md5StringFromString(_ string: String) -> String {
232 |
233 | let str = string.cString(using: String.Encoding.utf8)
234 | let strLen = CC_LONG(string.lengthOfBytes(using: String.Encoding.utf8))
235 | let digestLen = Int(CC_MD5_DIGEST_LENGTH)
236 | let result = UnsafeMutablePointer.allocate(capacity: digestLen);
237 |
238 | CC_MD5(str!, strLen, result);
239 |
240 | let hash = NSMutableString();
241 | for i in 0 ..< digestLen {
242 | hash.appendFormat("%02x", result[i]);
243 | }
244 | result.deinitialize();
245 |
246 | return String(format: hash as String)
247 | }
248 |
249 | fileprivate class func appVersionString() -> String {
250 |
251 | return Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
252 |
253 | }
254 | }
255 |
256 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 46;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | 4B5E92131D61D9F90047BBB5 /* XHNetworkCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B5E92121D61D9F90047BBB5 /* XHNetworkCache.swift */; };
11 | 4B75431B1D5DB8A4007D3C7E /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B75431A1D5DB8A4007D3C7E /* AppDelegate.swift */; };
12 | 4B7543221D5DB8A4007D3C7E /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 4B7543211D5DB8A4007D3C7E /* Assets.xcassets */; };
13 | 4B7543251D5DB8A4007D3C7E /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 4B7543231D5DB8A4007D3C7E /* LaunchScreen.storyboard */; };
14 | 4B75432E1D5DB942007D3C7E /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4B75432C1D5DB942007D3C7E /* ViewController.swift */; };
15 | 4B75432F1D5DB942007D3C7E /* ViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 4B75432D1D5DB942007D3C7E /* ViewController.xib */; };
16 | /* End PBXBuildFile section */
17 |
18 | /* Begin PBXFileReference section */
19 | 4B5E92121D61D9F90047BBB5 /* XHNetworkCache.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = XHNetworkCache.swift; sourceTree = ""; };
20 | 4B7543171D5DB8A4007D3C7E /* XHNetworkCacheSwiftExample.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = XHNetworkCacheSwiftExample.app; sourceTree = BUILT_PRODUCTS_DIR; };
21 | 4B75431A1D5DB8A4007D3C7E /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; };
22 | 4B7543211D5DB8A4007D3C7E /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
23 | 4B7543241D5DB8A4007D3C7E /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; };
24 | 4B7543261D5DB8A4007D3C7E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
25 | 4B75432C1D5DB942007D3C7E /* ViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; };
26 | 4B75432D1D5DB942007D3C7E /* ViewController.xib */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.xib; path = ViewController.xib; sourceTree = ""; };
27 | 4B7543331D5DB9FC007D3C7E /* XHNetworkCacheSwiftExample-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "XHNetworkCacheSwiftExample-Bridging-Header.h"; sourceTree = ""; };
28 | /* End PBXFileReference section */
29 |
30 | /* Begin PBXFrameworksBuildPhase section */
31 | 4B7543141D5DB8A4007D3C7E /* Frameworks */ = {
32 | isa = PBXFrameworksBuildPhase;
33 | buildActionMask = 2147483647;
34 | files = (
35 | );
36 | runOnlyForDeploymentPostprocessing = 0;
37 | };
38 | /* End PBXFrameworksBuildPhase section */
39 |
40 | /* Begin PBXGroup section */
41 | 4B5E92111D61D9F90047BBB5 /* XHNetworkCacheSwift */ = {
42 | isa = PBXGroup;
43 | children = (
44 | 4B5E92121D61D9F90047BBB5 /* XHNetworkCache.swift */,
45 | );
46 | path = XHNetworkCacheSwift;
47 | sourceTree = "";
48 | };
49 | 4B75430E1D5DB8A4007D3C7E = {
50 | isa = PBXGroup;
51 | children = (
52 | 4B7543191D5DB8A4007D3C7E /* XHNetworkCacheSwiftExample */,
53 | 4B5E92111D61D9F90047BBB5 /* XHNetworkCacheSwift */,
54 | 4B7543181D5DB8A4007D3C7E /* Products */,
55 | );
56 | sourceTree = "";
57 | };
58 | 4B7543181D5DB8A4007D3C7E /* Products */ = {
59 | isa = PBXGroup;
60 | children = (
61 | 4B7543171D5DB8A4007D3C7E /* XHNetworkCacheSwiftExample.app */,
62 | );
63 | name = Products;
64 | sourceTree = "";
65 | };
66 | 4B7543191D5DB8A4007D3C7E /* XHNetworkCacheSwiftExample */ = {
67 | isa = PBXGroup;
68 | children = (
69 | 4B75431A1D5DB8A4007D3C7E /* AppDelegate.swift */,
70 | 4B75432C1D5DB942007D3C7E /* ViewController.swift */,
71 | 4B75432D1D5DB942007D3C7E /* ViewController.xib */,
72 | 4B7543211D5DB8A4007D3C7E /* Assets.xcassets */,
73 | 4B7543231D5DB8A4007D3C7E /* LaunchScreen.storyboard */,
74 | 4B7543261D5DB8A4007D3C7E /* Info.plist */,
75 | 4B7543331D5DB9FC007D3C7E /* XHNetworkCacheSwiftExample-Bridging-Header.h */,
76 | );
77 | path = XHNetworkCacheSwiftExample;
78 | sourceTree = "";
79 | };
80 | /* End PBXGroup section */
81 |
82 | /* Begin PBXNativeTarget section */
83 | 4B7543161D5DB8A4007D3C7E /* XHNetworkCacheSwiftExample */ = {
84 | isa = PBXNativeTarget;
85 | buildConfigurationList = 4B7543291D5DB8A4007D3C7E /* Build configuration list for PBXNativeTarget "XHNetworkCacheSwiftExample" */;
86 | buildPhases = (
87 | 4B7543131D5DB8A4007D3C7E /* Sources */,
88 | 4B7543141D5DB8A4007D3C7E /* Frameworks */,
89 | 4B7543151D5DB8A4007D3C7E /* Resources */,
90 | );
91 | buildRules = (
92 | );
93 | dependencies = (
94 | );
95 | name = XHNetworkCacheSwiftExample;
96 | productName = XHNetworkCacheSwiftExample;
97 | productReference = 4B7543171D5DB8A4007D3C7E /* XHNetworkCacheSwiftExample.app */;
98 | productType = "com.apple.product-type.application";
99 | };
100 | /* End PBXNativeTarget section */
101 |
102 | /* Begin PBXProject section */
103 | 4B75430F1D5DB8A4007D3C7E /* Project object */ = {
104 | isa = PBXProject;
105 | attributes = {
106 | LastSwiftUpdateCheck = 0730;
107 | LastUpgradeCheck = 0800;
108 | ORGANIZATIONNAME = qiantou;
109 | TargetAttributes = {
110 | 4B7543161D5DB8A4007D3C7E = {
111 | CreatedOnToolsVersion = 7.3.1;
112 | LastSwiftMigration = 0800;
113 | };
114 | };
115 | };
116 | buildConfigurationList = 4B7543121D5DB8A4007D3C7E /* Build configuration list for PBXProject "XHNetworkCacheSwiftExample" */;
117 | compatibilityVersion = "Xcode 3.2";
118 | developmentRegion = English;
119 | hasScannedForEncodings = 0;
120 | knownRegions = (
121 | en,
122 | Base,
123 | );
124 | mainGroup = 4B75430E1D5DB8A4007D3C7E;
125 | productRefGroup = 4B7543181D5DB8A4007D3C7E /* Products */;
126 | projectDirPath = "";
127 | projectRoot = "";
128 | targets = (
129 | 4B7543161D5DB8A4007D3C7E /* XHNetworkCacheSwiftExample */,
130 | );
131 | };
132 | /* End PBXProject section */
133 |
134 | /* Begin PBXResourcesBuildPhase section */
135 | 4B7543151D5DB8A4007D3C7E /* Resources */ = {
136 | isa = PBXResourcesBuildPhase;
137 | buildActionMask = 2147483647;
138 | files = (
139 | 4B7543251D5DB8A4007D3C7E /* LaunchScreen.storyboard in Resources */,
140 | 4B75432F1D5DB942007D3C7E /* ViewController.xib in Resources */,
141 | 4B7543221D5DB8A4007D3C7E /* Assets.xcassets in Resources */,
142 | );
143 | runOnlyForDeploymentPostprocessing = 0;
144 | };
145 | /* End PBXResourcesBuildPhase section */
146 |
147 | /* Begin PBXSourcesBuildPhase section */
148 | 4B7543131D5DB8A4007D3C7E /* Sources */ = {
149 | isa = PBXSourcesBuildPhase;
150 | buildActionMask = 2147483647;
151 | files = (
152 | 4B75432E1D5DB942007D3C7E /* ViewController.swift in Sources */,
153 | 4B5E92131D61D9F90047BBB5 /* XHNetworkCache.swift in Sources */,
154 | 4B75431B1D5DB8A4007D3C7E /* AppDelegate.swift in Sources */,
155 | );
156 | runOnlyForDeploymentPostprocessing = 0;
157 | };
158 | /* End PBXSourcesBuildPhase section */
159 |
160 | /* Begin PBXVariantGroup section */
161 | 4B7543231D5DB8A4007D3C7E /* LaunchScreen.storyboard */ = {
162 | isa = PBXVariantGroup;
163 | children = (
164 | 4B7543241D5DB8A4007D3C7E /* Base */,
165 | );
166 | name = LaunchScreen.storyboard;
167 | sourceTree = "";
168 | };
169 | /* End PBXVariantGroup section */
170 |
171 | /* Begin XCBuildConfiguration section */
172 | 4B7543271D5DB8A4007D3C7E /* Debug */ = {
173 | isa = XCBuildConfiguration;
174 | buildSettings = {
175 | ALWAYS_SEARCH_USER_PATHS = NO;
176 | CLANG_ANALYZER_NONNULL = YES;
177 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
178 | CLANG_CXX_LIBRARY = "libc++";
179 | CLANG_ENABLE_MODULES = YES;
180 | CLANG_ENABLE_OBJC_ARC = YES;
181 | CLANG_WARN_BOOL_CONVERSION = YES;
182 | CLANG_WARN_CONSTANT_CONVERSION = YES;
183 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
184 | CLANG_WARN_EMPTY_BODY = YES;
185 | CLANG_WARN_ENUM_CONVERSION = YES;
186 | CLANG_WARN_INFINITE_RECURSION = YES;
187 | CLANG_WARN_INT_CONVERSION = YES;
188 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
189 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
190 | CLANG_WARN_UNREACHABLE_CODE = YES;
191 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
192 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
193 | COPY_PHASE_STRIP = NO;
194 | DEBUG_INFORMATION_FORMAT = dwarf;
195 | ENABLE_STRICT_OBJC_MSGSEND = YES;
196 | ENABLE_TESTABILITY = YES;
197 | GCC_C_LANGUAGE_STANDARD = gnu99;
198 | GCC_DYNAMIC_NO_PIC = NO;
199 | GCC_NO_COMMON_BLOCKS = YES;
200 | GCC_OPTIMIZATION_LEVEL = 0;
201 | GCC_PREPROCESSOR_DEFINITIONS = (
202 | "DEBUG=1",
203 | "$(inherited)",
204 | );
205 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
206 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
207 | GCC_WARN_UNDECLARED_SELECTOR = YES;
208 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
209 | GCC_WARN_UNUSED_FUNCTION = YES;
210 | GCC_WARN_UNUSED_VARIABLE = YES;
211 | IPHONEOS_DEPLOYMENT_TARGET = 8.0;
212 | MTL_ENABLE_DEBUG_INFO = YES;
213 | ONLY_ACTIVE_ARCH = YES;
214 | SDKROOT = iphoneos;
215 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
216 | };
217 | name = Debug;
218 | };
219 | 4B7543281D5DB8A4007D3C7E /* Release */ = {
220 | isa = XCBuildConfiguration;
221 | buildSettings = {
222 | ALWAYS_SEARCH_USER_PATHS = NO;
223 | CLANG_ANALYZER_NONNULL = YES;
224 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x";
225 | CLANG_CXX_LIBRARY = "libc++";
226 | CLANG_ENABLE_MODULES = YES;
227 | CLANG_ENABLE_OBJC_ARC = YES;
228 | CLANG_WARN_BOOL_CONVERSION = YES;
229 | CLANG_WARN_CONSTANT_CONVERSION = YES;
230 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
231 | CLANG_WARN_EMPTY_BODY = YES;
232 | CLANG_WARN_ENUM_CONVERSION = YES;
233 | CLANG_WARN_INFINITE_RECURSION = YES;
234 | CLANG_WARN_INT_CONVERSION = YES;
235 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
236 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
237 | CLANG_WARN_UNREACHABLE_CODE = YES;
238 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
239 | "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
240 | COPY_PHASE_STRIP = NO;
241 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
242 | ENABLE_NS_ASSERTIONS = NO;
243 | ENABLE_STRICT_OBJC_MSGSEND = YES;
244 | GCC_C_LANGUAGE_STANDARD = gnu99;
245 | GCC_NO_COMMON_BLOCKS = YES;
246 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
247 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
248 | GCC_WARN_UNDECLARED_SELECTOR = YES;
249 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
250 | GCC_WARN_UNUSED_FUNCTION = YES;
251 | GCC_WARN_UNUSED_VARIABLE = YES;
252 | IPHONEOS_DEPLOYMENT_TARGET = 8.0;
253 | MTL_ENABLE_DEBUG_INFO = NO;
254 | SDKROOT = iphoneos;
255 | SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule";
256 | VALIDATE_PRODUCT = YES;
257 | };
258 | name = Release;
259 | };
260 | 4B75432A1D5DB8A4007D3C7E /* Debug */ = {
261 | isa = XCBuildConfiguration;
262 | buildSettings = {
263 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
264 | CLANG_ENABLE_MODULES = YES;
265 | INFOPLIST_FILE = XHNetworkCacheSwiftExample/Info.plist;
266 | IPHONEOS_DEPLOYMENT_TARGET = 8.0;
267 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
268 | PRODUCT_BUNDLE_IDENTIFIER = CoderZhuXH.XHNetworkCacheSwiftExample;
269 | PRODUCT_NAME = "$(TARGET_NAME)";
270 | SWIFT_OBJC_BRIDGING_HEADER = "XHNetworkCacheSwiftExample/XHNetworkCacheSwiftExample-Bridging-Header.h";
271 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
272 | SWIFT_VERSION = 3.0;
273 | };
274 | name = Debug;
275 | };
276 | 4B75432B1D5DB8A4007D3C7E /* Release */ = {
277 | isa = XCBuildConfiguration;
278 | buildSettings = {
279 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
280 | CLANG_ENABLE_MODULES = YES;
281 | INFOPLIST_FILE = XHNetworkCacheSwiftExample/Info.plist;
282 | IPHONEOS_DEPLOYMENT_TARGET = 8.0;
283 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
284 | PRODUCT_BUNDLE_IDENTIFIER = CoderZhuXH.XHNetworkCacheSwiftExample;
285 | PRODUCT_NAME = "$(TARGET_NAME)";
286 | SWIFT_OBJC_BRIDGING_HEADER = "XHNetworkCacheSwiftExample/XHNetworkCacheSwiftExample-Bridging-Header.h";
287 | SWIFT_VERSION = 3.0;
288 | };
289 | name = Release;
290 | };
291 | /* End XCBuildConfiguration section */
292 |
293 | /* Begin XCConfigurationList section */
294 | 4B7543121D5DB8A4007D3C7E /* Build configuration list for PBXProject "XHNetworkCacheSwiftExample" */ = {
295 | isa = XCConfigurationList;
296 | buildConfigurations = (
297 | 4B7543271D5DB8A4007D3C7E /* Debug */,
298 | 4B7543281D5DB8A4007D3C7E /* Release */,
299 | );
300 | defaultConfigurationIsVisible = 0;
301 | defaultConfigurationName = Release;
302 | };
303 | 4B7543291D5DB8A4007D3C7E /* Build configuration list for PBXNativeTarget "XHNetworkCacheSwiftExample" */ = {
304 | isa = XCConfigurationList;
305 | buildConfigurations = (
306 | 4B75432A1D5DB8A4007D3C7E /* Debug */,
307 | 4B75432B1D5DB8A4007D3C7E /* Release */,
308 | );
309 | defaultConfigurationIsVisible = 0;
310 | defaultConfigurationName = Release;
311 | };
312 | /* End XCConfigurationList section */
313 | };
314 | rootObject = 4B75430F1D5DB8A4007D3C7E /* Project object */;
315 | }
316 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample.xcodeproj/project.xcworkspace/contents.xcworkspacedata:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample.xcodeproj/project.xcworkspace/xcuserdata/xiaohui.xcuserdatad/UserInterfaceState.xcuserstate:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CoderZhuXH/XHNetworkCacheSwift/768ca4e2a1796a0cd1d05b5c7a9906e19ef4f2db/XHNetworkCacheSwiftExample.xcodeproj/project.xcworkspace/xcuserdata/xiaohui.xcuserdatad/UserInterfaceState.xcuserstate
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample.xcodeproj/xcuserdata/xiaohui.xcuserdatad/xcschemes/XHNetworkCacheSwiftExample.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
32 |
33 |
39 |
40 |
41 |
42 |
43 |
44 |
54 |
56 |
62 |
63 |
64 |
65 |
66 |
67 |
73 |
75 |
81 |
82 |
83 |
84 |
86 |
87 |
90 |
91 |
92 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample.xcodeproj/xcuserdata/xiaohui.xcuserdatad/xcschemes/xcschememanagement.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | SchemeUserState
6 |
7 | XHNetworkCacheSwiftExample.xcscheme
8 |
9 | orderHint
10 | 0
11 |
12 |
13 | SuppressBuildableAutocreation
14 |
15 | 4B7543161D5DB8A4007D3C7E
16 |
17 | primary
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample/AppDelegate.swift:
--------------------------------------------------------------------------------
1 | //
2 | // AppDelegate.swift
3 | // XHNetworkCacheSwiftExample
4 | //
5 | // Created by xiaohui on 16/8/12.
6 | // Copyright © 2016年 CoderZhuXH. All rights reserved.
7 | // 代码地址:https://github.com/CoderZhuXH/XHNetworkCacheSwift
8 |
9 | import UIKit
10 |
11 | @UIApplicationMain
12 | class AppDelegate: UIResponder, UIApplicationDelegate {
13 |
14 | var window: UIWindow?
15 |
16 |
17 | func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
18 |
19 | window = UIWindow(frame:UIScreen.main.bounds)
20 | window?.backgroundColor = UIColor.white
21 |
22 |
23 | window?.rootViewController = UINavigationController.init(rootViewController: ViewController())
24 |
25 |
26 | window?.makeKeyAndVisible()
27 | // Override point for customization after application launch.
28 | return true
29 | }
30 |
31 | func applicationWillResignActive(_ application: UIApplication) {
32 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
33 | // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
34 | }
35 |
36 | func applicationDidEnterBackground(_ application: UIApplication) {
37 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
38 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
39 | }
40 |
41 | func applicationWillEnterForeground(_ application: UIApplication) {
42 | // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
43 | }
44 |
45 | func applicationDidBecomeActive(_ application: UIApplication) {
46 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
47 | }
48 |
49 | func applicationWillTerminate(_ application: UIApplication) {
50 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
51 | }
52 |
53 |
54 | }
55 |
56 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "size" : "29x29",
6 | "scale" : "2x"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "size" : "29x29",
11 | "scale" : "3x"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "size" : "40x40",
16 | "scale" : "2x"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "size" : "40x40",
21 | "scale" : "3x"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "size" : "60x60",
26 | "scale" : "2x"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "size" : "60x60",
31 | "scale" : "3x"
32 | }
33 | ],
34 | "info" : {
35 | "version" : 1,
36 | "author" : "xcode"
37 | }
38 | }
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample/Base.lproj/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | APPL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | UILaunchStoryboardName
26 | LaunchScreen
27 | UIRequiredDeviceCapabilities
28 |
29 | armv7
30 |
31 | UISupportedInterfaceOrientations
32 |
33 | UIInterfaceOrientationPortrait
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample/ViewController.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ViewController.swift
3 | // XHNetworkCacheSwiftExample
4 | //
5 | // Created by xiaohui on 16/8/12.
6 | // Copyright © 2016年 CoderZhuXH. All rights reserved.
7 | // 代码地址:https://github.com/CoderZhuXH/XHNetworkCacheSwift
8 |
9 | import UIKit
10 |
11 | class ViewController: UIViewController {
12 |
13 | @IBOutlet weak var textLab: UILabel!
14 |
15 | /**
16 | * 模拟数据请求URL
17 | */
18 | let URLString = "http://www.returnoc.com"
19 |
20 | /**
21 | * 模拟服务器请求数据
22 | */
23 | let responseObject = [
24 | "time" : "1444524177",
25 | "isauth" : "0",
26 | "openid" : "1728484287",
27 | "sex" : "男",
28 | "city" : "",
29 | "cover" : "http://tp4.sinaimg.cn/1728484287/180/5736236738/1",
30 | "logintime" : "1445267749",
31 | "name" : "",
32 | "group" : "3",
33 | "loginhit" : "4",
34 | "id" : "234328",
35 | "phone" : "",
36 | "nicheng" : "辉Allen",
37 | "apptoken" : "bae4c30113151270174f724f450779bc",
38 | "face" : "http://tp4.sinaimg.cn/1728484287/180/5736236738/1",
39 | "desc" : "比你牛B的人都在努力,你还有什么理由偷懒!",
40 | "infoverify" : "1"
41 | ]
42 |
43 | override func viewDidLoad() {
44 | super.viewDidLoad()
45 |
46 | self.navigationItem.title = "XHNetworkCacheSwiftExample"
47 |
48 | textLab.text = "请看控制台打印 \n 详见Github: https://github.com/CoderZhuXH/XHNetworkCache-Swift"
49 |
50 |
51 | // Do any additional setup after loading the view.
52 | }
53 |
54 | /**
55 | * (同步)写入/更新缓存
56 | */
57 | @IBAction func save(_ sender: UIButton) {
58 |
59 | if XHNetworkCache.saveJsonResponseToCacheFile(responseObject as AnyObject, URL: URLString)
60 | {
61 | print("(同步)保存/更新成功")
62 | }
63 | else
64 | {
65 |
66 | print("(同步)保存/更新失败")
67 | }
68 |
69 | }
70 |
71 | /**
72 | * (异步)写入/更新缓存
73 | */
74 | @IBAction func save_async(_ sender: UIButton) {
75 |
76 | XHNetworkCache.save_asyncJsonResponseToCacheFile(responseObject as AnyObject, URL: URLString) { (result) in
77 |
78 | if(result)
79 | {
80 | print("(异步)保存/更新成功")
81 | }
82 | else
83 | {
84 | print("(异步)保存/更新成功")
85 | }
86 | }
87 |
88 | }
89 |
90 | /**
91 | * 获取缓存数据
92 | */
93 | @IBAction func getCache(_ sender: UIButton) {
94 |
95 | if let json = XHNetworkCache.cacheJsonWithURL(URLString)
96 | {
97 | print(json)
98 | }
99 | }
100 |
101 | /**
102 | * 缓存数据大小(M)
103 | */
104 | @IBAction func cacheSize(_ sender: UIButton) {
105 |
106 |
107 | let size = XHNetworkCache.cacheSize()
108 |
109 | print("缓存大小(M)=\(size)")
110 |
111 | }
112 |
113 | /**
114 | * 缓存路径
115 | */
116 | @IBAction func cachePath(_ sender: UIButton) {
117 |
118 | let path = XHNetworkCache.cachePath()
119 | print("缓存路径=" + path)
120 |
121 | }
122 |
123 | /**
124 | * 清除缓存
125 | */
126 | @IBAction func clearCache(_ sender: UIButton) {
127 |
128 | if XHNetworkCache.clearCache()
129 | {
130 | print("清除缓存成功")
131 | }
132 | else
133 | {
134 | print("清除缓存失败")
135 |
136 | }
137 | }
138 |
139 | override func didReceiveMemoryWarning() {
140 | super.didReceiveMemoryWarning()
141 | // Dispose of any resources that can be recreated.
142 | }
143 |
144 |
145 | /*
146 | // MARK: - Navigation
147 |
148 | // In a storyboard-based application, you will often want to do a little preparation before navigation
149 | override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
150 | // Get the new view controller using segue.destinationViewController.
151 | // Pass the selected object to the new view controller.
152 | }
153 | */
154 |
155 | }
156 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample/ViewController.xib:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
33 |
48 |
63 |
77 |
92 |
106 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
--------------------------------------------------------------------------------
/XHNetworkCacheSwiftExample/XHNetworkCacheSwiftExample-Bridging-Header.h:
--------------------------------------------------------------------------------
1 | //
2 | // Use this file to import your target's public headers that you would like to expose to Swift.
3 | // 代码地址:https://github.com/CoderZhuXH/XHNetworkCacheSwift
4 |
5 |
6 | #import
--------------------------------------------------------------------------------