Skip to content

Commit

Permalink
feat: Optimization for Chunk-Downloads (#27)
Browse files Browse the repository at this point in the history
  • Loading branch information
wzxha authored Jan 8, 2024
1 parent 7cc40c3 commit 28a0561
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class AliyunpanAppJumper {
}

func jump(to url: URL) async throws -> String {
guard Platform.canOpenURL(url) else {
guard await Platform.canOpenURL(url) else {
throw AliyunpanError.AuthorizeError.notInstalledApp
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public class AliyunpanDownloadTask: NSObject, Identifiable {
public let file: AliyunpanFile
let destination: URL

private let chunkSize = 4_000_000
private let chunkSize: Int64
private let downloadURLActor = DownloadURLActor()
private let fileManager = FileManager.default

Expand All @@ -88,12 +88,17 @@ public class AliyunpanDownloadTask: NSObject, Identifiable {
private(set) var urlSession: URLSession?

private var writedSize: Int64 = 0

@ThreadSafe
var unfinishedChunks: [AliyunpanDownloadChunk] = []

init(file: AliyunpanFile, destination: URL, delegate: AliyunpanDownloadTaskDelegate?) {
self.file = file
self.destination = destination
self.delegate = delegate
// 根据文件大小动态设置分片大小,来降低内存占用
// 最小为4M
self.chunkSize = max(4_000_000, (file.size ?? 0) / 1000)
super.init()
delegate?.downloadTask(self, didUpdateState: state)
}
Expand Down Expand Up @@ -176,7 +181,7 @@ extension AliyunpanDownloadTask {
}

var chunks: [AliyunpanDownloadChunk] {
stride(from: 0, to: totalSize, by: chunkSize).map {
stride(from: 0, to: totalSize, by: Int64.Stride(chunkSize)).map {
AliyunpanDownloadChunk(start: $0, end: min($0 + Int64(chunkSize), totalSize))
}
}
Expand Down
3 changes: 2 additions & 1 deletion Sources/AliyunpanSDK/Platform.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import TVUIKit
#endif

class Platform {

@MainActor
static func canOpenURL(_ url: URL) -> Bool {
#if canImport(UIKit) || canImport(TVUIKit)
return UIApplication.shared.canOpenURL(url)
Expand All @@ -29,6 +29,7 @@ class Platform {
#endif
}

@MainActor
static func open(_ url: URL) async {
#if canImport(UIKit) || canImport(TVUIKit)
await UIApplication.shared.open(url)
Expand Down

0 comments on commit 28a0561

Please sign in to comment.