Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniels committed Jan 8, 2020
1 parent da09734 commit c0edaf6
Show file tree
Hide file tree
Showing 29 changed files with 113 additions and 87 deletions.
2 changes: 1 addition & 1 deletion Demo/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleDisplayName</key>
<string>Tiercel</string>
<string>$(PRODUCT_NAME)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
Expand Down
22 changes: 22 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "Tiercel",
platforms: [.iOS(.v8)],
products: [
// Products define the executables and libraries produced by a package, and make them visible to other packages.
.library(
name: "Tiercel",
targets: ["Tiercel"]),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "Tiercel",
path: "Sources")
]
)
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -32,29 +32,29 @@ public class DownloadTask: Task<DownloadTask> {
case resumeData
}

internal var task: URLSessionDownloadTask? {
internal var sessionTask: URLSessionDownloadTask? {
willSet {
task?.removeObserver(self, forKeyPath: "currentRequest")
sessionTask?.removeObserver(self, forKeyPath: "currentRequest")
}
didSet {
task?.addObserver(self, forKeyPath: "currentRequest", options: [.new], context: nil)
sessionTask?.addObserver(self, forKeyPath: "currentRequest", options: [.new], context: nil)
}
}

public var originalRequest: URLRequest? {
task?.originalRequest
sessionTask?.originalRequest
}

public var currentRequest: URLRequest? {
task?.currentRequest
sessionTask?.currentRequest
}

public var response: URLResponse? {
task?.response
sessionTask?.response
}

public var statusCode: Int? {
(task?.response as? HTTPURLResponse)?.statusCode
(sessionTask?.response as? HTTPURLResponse)?.statusCode
}

public var filePath: String {
Expand Down Expand Up @@ -130,7 +130,7 @@ public class DownloadTask: Task<DownloadTask> {
try container.encodeIfPresent(resumeData, forKey: .resumeData)
}

public required init(from decoder: Decoder) throws {
internal required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
Expand All @@ -154,14 +154,14 @@ public class DownloadTask: Task<DownloadTask> {
}

deinit {
task?.removeObserver(self, forKeyPath: "currentRequest")
sessionTask?.removeObserver(self, forKeyPath: "currentRequest")
NotificationCenter.default.removeObserver(self)
}

@objc private func fixDelegateMethodError() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.task?.suspend()
self.task?.resume()
self.sessionTask?.suspend()
self.sessionTask?.resume()
}
}

Expand All @@ -186,7 +186,7 @@ extension DownloadTask {
progress.totalUnitCount = length
}
succeeded()
manager?.process()
manager?.determineStatus()
return
}
download()
Expand All @@ -204,7 +204,7 @@ extension DownloadTask {
}
case .succeeded:
succeeded()
manager.process()
manager.determineStatus()
case .running:
TiercelLog("[downloadTask] running", identifier: manager.identifier, url: url)
default: break
Expand All @@ -216,11 +216,11 @@ extension DownloadTask {
if let resumeData = resumeData {
cache.retrieveTmpFile(self)
if #available(iOS 10.2, *) {
task = session?.downloadTask(withResumeData: resumeData)
sessionTask = session?.downloadTask(withResumeData: resumeData)
} else if #available(iOS 10.0, *) {
task = session?.correctedDownloadTask(withResumeData: resumeData)
sessionTask = session?.correctedDownloadTask(withResumeData: resumeData)
} else {
task = session?.downloadTask(withResumeData: resumeData)
sessionTask = session?.downloadTask(withResumeData: resumeData)
}
} else {
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 0)
Expand All @@ -229,12 +229,12 @@ extension DownloadTask {
request.setValue(value, forHTTPHeaderField: key)
}
}
task = session?.downloadTask(with: request)
sessionTask = session?.downloadTask(with: request)
}
speed = 0
progress.setUserInfoObject(progress.completedUnitCount, forKey: .fileCompletedCountKey)

task?.resume()
sessionTask?.resume()

if startDate == 0 {
startDate = Date().timeIntervalSince1970
Expand All @@ -252,7 +252,7 @@ extension DownloadTask {

if status == .running {
status = .willSuspend
task?.cancel(byProducingResumeData: { _ in })
sessionTask?.cancel(byProducingResumeData: { _ in })
}

if status == .waiting {
Expand All @@ -262,7 +262,7 @@ extension DownloadTask {
controlExecuter?.execute(self)
failureExecuter?.execute(self)

manager?.process()
manager?.determineStatus()
}
}

Expand All @@ -271,14 +271,14 @@ extension DownloadTask {
controlExecuter = Executer(onMainQueue: onMainQueue, handler: handler)
if status == .running {
status = .willCancel
task?.cancel()
sessionTask?.cancel()
} else {
status = .willCancel
didCancelOrRemove()
TiercelLog("[downloadTask] did cancel", identifier: manager?.identifier ?? "", url: url)
controlExecuter?.execute(self)
failureExecuter?.execute(self)
manager?.process()
manager?.determineStatus()
}
}

Expand All @@ -288,14 +288,14 @@ extension DownloadTask {
controlExecuter = Executer(onMainQueue: onMainQueue, handler: handler)
if status == .running {
status = .willRemove
task?.cancel()
sessionTask?.cancel()
} else {
status = .willRemove
didCancelOrRemove()
TiercelLog("[downloadTask] did remove", identifier: manager?.identifier ?? "", url: url)
controlExecuter?.execute(self)
failureExecuter?.execute(self)
manager?.process()
manager?.determineStatus()
}
}

Expand Down Expand Up @@ -362,7 +362,7 @@ extension DownloadTask {
validateFile()
}

private func detectStatus(error: Error?, statusCode: Int) {
private func determineStatus(error: Error?, statusCode: Int) {
if statusCode != 200 {
status = .failed
}
Expand Down Expand Up @@ -523,10 +523,10 @@ extension DownloadTask {
if error == nil && statusCode == 200 {
succeeded()
} else {
detectStatus(error: error, statusCode: statusCode)
determineStatus(error: error, statusCode: statusCode)
}

manager?.process()
manager?.determineStatus()
}

}
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ public class SessionManager {
shouldCreatSession = true
operationQueue.sync {
createSession()
updateStatus()
restoreStatus()
}
}

Expand All @@ -262,37 +262,7 @@ public class SessionManager {
completion?()
}

private func updateStatus() {
if self.tasks.isEmpty {
return
}
session?.getTasksWithCompletionHandler { [weak self] (dataTasks, uploadTasks, downloadTasks) in
guard let self = self else { return }
downloadTasks.forEach { downloadTask in
if downloadTask.state == .running,
let currentURL = downloadTask.currentRequest?.url,
let task = self.fetchTask(currentURL: currentURL) {
task.status = .running
task.task = downloadTask
TiercelLog("[downloadTask] runing", identifier: self.identifier, url: task.url)
}
}

// 处理mananger状态
let isRunning = self.tasks.filter { $0.status == .running }.count > 0
if isRunning {
self.didStart()
return
}

let isSucceeded = self.tasks.allSatisfy { $0.status == .succeeded }
let isCompleted = isSucceeded ? isSucceeded : self.tasks.allSatisfy { $0.status == .succeeded || $0.status == .failed }

if !self.shouldComplete(isCompleted, isSucceeded) {
self.shouldSuspend()
}
}
}


}
Expand Down Expand Up @@ -518,6 +488,38 @@ extension SessionManager {
// MARK: - status handle
extension SessionManager {

private func restoreStatus() {
if self.tasks.isEmpty {
return
}
session?.getTasksWithCompletionHandler { [weak self] (dataTasks, uploadTasks, downloadTasks) in
guard let self = self else { return }
var isRunning = false
downloadTasks.forEach { downloadTask in
if downloadTask.state == .running,
let currentURL = downloadTask.currentRequest?.url,
let task = self.fetchTask(currentURL: currentURL) {
task.status = .running
task.sessionTask = downloadTask
TiercelLog("[downloadTask] runing", identifier: self.identifier, url: task.url)
isRunning = true
}
}
// 处理mananger状态
if isRunning {
self.didStart()
return
}

let isSucceeded = self.tasks.allSatisfy { $0.status == .succeeded }
let isCompleted = isSucceeded ? isSucceeded : self.tasks.allSatisfy { $0.status == .succeeded || $0.status == .failed }

if !self.shouldComplete(isCompleted, isSucceeded) {
self.shouldSuspend()
}
}
}

internal func didStart() {
if status != .running {
createTimer()
Expand Down Expand Up @@ -546,7 +548,7 @@ extension SessionManager {
}
}

internal func process() {
internal func determineStatus() {
cache.storeTasks(tasks)

let isSucceeded = tasks.allSatisfy { $0.status == .succeeded }
Expand Down
20 changes: 10 additions & 10 deletions Tiercel/General/Task.swift → Sources/General/Task.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ extension Task {
}
}

public class Task<T>: NSObject, NSCoding, Codable {
public class Task<TaskType>: NSObject, NSCoding, Codable {

private enum CodingKeys: CodingKey {
case url
Expand Down Expand Up @@ -65,15 +65,15 @@ public class Task<T>: NSObject, NSCoding, Codable {

internal var verificationType: FileVerificationType = .md5

internal var progressExecuter: Executer<T>?
internal var progressExecuter: Executer<TaskType>?

internal var successExecuter: Executer<T>?
internal var successExecuter: Executer<TaskType>?

internal var failureExecuter: Executer<T>?
internal var failureExecuter: Executer<TaskType>?

internal var controlExecuter: Executer<T>?
internal var controlExecuter: Executer<TaskType>?

internal var validateExecuter: Executer<T>?
internal var validateExecuter: Executer<TaskType>?

internal let dataQueue = DispatchQueue(label: "com.Tiercel.Task.dataQueue")

Expand Down Expand Up @@ -314,7 +314,7 @@ public class Task<T>: NSObject, NSCoding, Codable {



internal func execute(_ Executer: Executer<T>?) {
internal func execute(_ Executer: Executer<TaskType>?) {

}

Expand All @@ -323,7 +323,7 @@ public class Task<T>: NSObject, NSCoding, Codable {

extension Task {
@discardableResult
public func progress(onMainQueue: Bool = true, _ handler: @escaping Handler<T>) -> Self {
public func progress(onMainQueue: Bool = true, _ handler: @escaping Handler<TaskType>) -> Self {
return operationQueue.sync {
progressExecuter = Executer(onMainQueue: onMainQueue, handler: handler)
return self
Expand All @@ -332,7 +332,7 @@ extension Task {
}

@discardableResult
public func success(onMainQueue: Bool = true, _ handler: @escaping Handler<T>) -> Self {
public func success(onMainQueue: Bool = true, _ handler: @escaping Handler<TaskType>) -> Self {
operationQueue.sync {
successExecuter = Executer(onMainQueue: onMainQueue, handler: handler)
}
Expand All @@ -346,7 +346,7 @@ extension Task {
}

@discardableResult
public func failure(onMainQueue: Bool = true, _ handler: @escaping Handler<T>) -> Self {
public func failure(onMainQueue: Bool = true, _ handler: @escaping Handler<TaskType>) -> Self {
operationQueue.sync {
failureExecuter = Executer(onMainQueue: onMainQueue, handler: handler)
}
Expand Down
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion Tiercel/Info.plist → Sources/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<key>CFBundlePackageType</key>
<string>FMWK</string>
<key>CFBundleShortVersionString</key>
<string>2.3.0</string>
<string>$(MARKETING_VERSION)</string>
<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
<key>NSPrincipalClass</key>
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
Loading

0 comments on commit c0edaf6

Please sign in to comment.