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

Clean up background session debug panel Swift UI #382

Merged
merged 2 commits into from
Dec 13, 2023
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class ActionRequestHandler: NSObject, NSExtensionRequestHandling {
client = DropboxClientsManager.authorizedClient
}

TestUtilities.createFileToUpload(sizeInMBs: 1)
TestUtilities.createFileToUpload(sizeInKBs: 1000)
let fileName = "/test_action_extension.txt"
let path = TestConstants.dropboxTestFolder + fileName
let input = TestConstants.fileToUpload
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,75 +7,34 @@ import SwiftyDropbox

@available(iOS 16.0, *)
struct DebugBackgroundSession: View {
@State var viewModel = DebugBackgroundSessionViewModel()
@State var showFileBrowser = false
@State var showLogBrowser = false
@StateObject var viewModel = DebugBackgroundSessionViewModel()

let debugLogFileURL: URL
let debugLogFileURL: URL?

var body: some View {
VStack {
ScrollView {
VStack(alignment: .leading, spacing: 3) {
HStack {
Button("Start Downloads", action: viewModel.startDownloads)
Button("Create Dropbox Folder", action: viewModel.createDropboxTestFolder)
.frame(maxWidth: .infinity, alignment: .trailing)
}
HStack {
Button("Start Uploads", action: viewModel.startUploads)
Button("Delete Dropbox Folder", action: viewModel.deleteDropboxTestFolder)
.frame(maxWidth: .infinity, alignment: .trailing)
}
HStack {
Button("Create Local Folder", action: viewModel.createLocalDownloadsFolder)
Button("Delete Local Downloads", action: viewModel.deleteLocalDownloads)
.frame(maxWidth: .infinity, alignment: .trailing)
}
HStack {
Text("Number of Downloads:")
Spacer(minLength: 100)
TextField("Enter number of downloads", value: $viewModel.numberOfDownloads, formatter: NumberFormatter())
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.numbersAndPunctuation)
.submitLabel(.done)
}
HStack {
Text("Number of Uploads:")
Spacer(minLength: 100)
TextField("Enter number of uploads", value: $viewModel.numberOfUploads, formatter: NumberFormatter())
.textFieldStyle(RoundedBorderTextFieldStyle())
.keyboardType(.numbersAndPunctuation)
.submitLabel(.done)
}
HStack {
Text("MB Size of Upload:")
Spacer(minLength: 100)
TextField("Enter a size in MB", text: viewModel.sizeOfUploadBinding)
.keyboardType(.numbersAndPunctuation)
.submitLabel(.done)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
}

VStack(alignment: .leading, spacing: 16) {
debugActionButtons
debugTextFields
Toggle(isOn: $viewModel.exitOnBackgrounding) {
Text("Exit on next didEnterBackground")
}
Button("View downloaded files", action: {
showFileBrowser = true
})
viewModel.showFileBrowser = true
}).buttonStyle(BlueButton())
Button("View logs", action: {
showLogBrowser = true
})
viewModel.showLogBrowser = true
}).buttonStyle(BlueButton())
}
.padding()
}
}
.fullScreenCover(isPresented: $showFileBrowser) {
FileBrowserView(localURL: TestConstants.localDownloadFolder)
.fullScreenCover(isPresented: $viewModel.showFileBrowser) {
MakeFileBrowserView(localURL: TestConstants.localDownloadFolder)
}
.fullScreenCover(isPresented: $showLogBrowser) {
FileTextView(fileURL: debugLogFileURL)
.fullScreenCover(isPresented: $viewModel.showLogBrowser) {
MakeFileTextView(fileURL: debugLogFileURL)
}
.onReceive(NotificationCenter.default.publisher(for: UIApplication.didEnterBackgroundNotification)) { _ in
if viewModel.exitOnBackgrounding {
Expand All @@ -84,11 +43,77 @@ struct DebugBackgroundSession: View {
}
}
}

var debugActionButtons: some View {
VStack {
HStack {
Button("Start Downloads", action: viewModel.startDownloads)
Button("Create Dropbox Folder", action: viewModel.createDropboxTestFolder)
}
HStack {
Button("Start Uploads", action: viewModel.startUploads)
Button("Delete Dropbox Folder", action: viewModel.deleteDropboxTestFolder)
}
HStack {
Button("Create Local Folder", action: viewModel.createLocalDownloadsFolder)
Button("Delete Local Downloads", action: viewModel.deleteLocalDownloads)
}
}
.buttonStyle(BlueButton())
}

var debugTextFields: some View {
VStack {
HStack {
Text("Number of Downloads:")
.frame(maxWidth: .infinity, alignment: .leading)
TextField("Enter number of downloads", value: $viewModel.numberOfDownloads, formatter: NumberFormatter())
.textFieldStyle(BackgroundDebugTextField())
}
HStack {
Text("Number of Uploads:")
.frame(maxWidth: .infinity, alignment: .leading)
TextField("Enter number of uploads", value: $viewModel.numberOfUploads, formatter: NumberFormatter())
.textFieldStyle(BackgroundDebugTextField())
}
HStack {
Text("KB Size of Upload:")
.frame(maxWidth: .infinity, alignment: .leading)
TextField("Enter a size in KB", text: $viewModel.sizeOfUpload)
.textFieldStyle(BackgroundDebugTextField())
}
}
}
}

@available(iOS 16.0, *)
struct BlueButton: ButtonStyle {
func makeBody(configuration: Configuration) -> some View {
configuration.label
.frame(maxWidth: .infinity)
.font(.caption)
.fontWeight(.bold)
.padding()
.background(configuration.isPressed ? .indigo : .blue )
.foregroundStyle(.white)
.clipShape(Capsule())
}
}

@available(iOS 16.0, *)
struct BackgroundDebugTextField: TextFieldStyle {
func _body(configuration: TextField<Self._Label>) -> some View {
configuration
.keyboardType(.numbersAndPunctuation)
.submitLabel(.done)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(maxWidth: .infinity)
}
}

@available(iOS 16.0, *)
struct DebugBackgroundSession_Previews: PreviewProvider {
static var previews: some View {
DebugBackgroundSession(debugLogFileURL: URL(string: NSTemporaryDirectory())!)
DebugBackgroundSession(debugLogFileURL: nil)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,13 @@ import SwiftUI
import SwiftyDropbox

@available(iOS 16.0, *)
class DebugBackgroundSessionViewModel {
var numberOfDownloads: Int = 0
var numberOfUploads: Int = 0
var sizeOfDownload: Int = 0
var sizeOfUpload: String = ""
var exitOnBackgrounding: Bool = false

var sizeOfUploadBinding: Binding<String> {
Binding<String>(
get: { self.sizeOfUpload },
set: { newValue in
if Float(newValue) != nil {
self.sizeOfUpload = newValue
}
}
)
}
class DebugBackgroundSessionViewModel: ObservableObject {
@Published var numberOfDownloads: Int = 0
@Published var numberOfUploads: Int = 0
@Published var sizeOfUpload: String = ""
@Published var exitOnBackgrounding: Bool = false
@Published var showFileBrowser = false
@Published var showLogBrowser = false

func startDownloads() {
for i in 0 ..< numberOfDownloads {
Expand All @@ -39,7 +29,7 @@ class DebugBackgroundSessionViewModel {
}

func startUploads() {
TestUtilities.createFileToUpload(sizeInMBs: Double(sizeOfUpload) ?? 1)
TestUtilities.createFileToUpload(sizeInKBs: Double(sizeOfUpload) ?? 1)

for i in 0 ..< numberOfUploads {
let path = TestConstants.dropboxTestFolder + "/test_\(i).txt"
Expand Down
84 changes: 51 additions & 33 deletions TestSwiftyDropbox/TestSwiftyDropbox_iOS/FileBrowserView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,66 +4,84 @@

import SwiftUI

@available(iOS 16.0, *)
func MakeFileBrowserView(localURL: URL?) -> FileBrowserView {
FileBrowserView(viewModel: FileBrowserViewModel(localURL: localURL))
}

@available(iOS 16.0, *)
class FileBrowserViewModel: ObservableObject {
let localURL: URL?
@Published var files: [URL] = []
@Published var showAlert = false
@Published var selectedFileContent: String = ""

init(localURL: URL?) {
self.localURL = localURL

let fileManager = FileManager.default

guard let localURL = localURL else {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be a failable initializer instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In this case we're trying to make a view model, just one that doesn't actually have file access

return
}

do {
let fileURLs = try fileManager.contentsOfDirectory(at: localURL, includingPropertiesForKeys: nil)
files = fileURLs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent })
} catch {
print("Error loading files: \(error)")
}
}

func showFile(fileURL: URL) -> () -> Void {
{
do {
self.selectedFileContent = String(try String(contentsOf: fileURL).prefix(10_000))
self.showAlert = true
} catch {
print("Error reading file: \(error)")
}
}
}
}

@available(iOS 16.0, *)
struct FileBrowserView: View {
@Environment(\.presentationMode) var presentationMode
let localURL: URL
@State private var files: [URL] = []
@State private var showAlert = false
@State private var selectedFileContent: String = ""
@Environment(\.dismiss) private var dismiss
@ObservedObject var viewModel: FileBrowserViewModel

var body: some View {
NavigationView {
VStack {
Text("Files Count: \(files.count)")
if files.isEmpty {
Text("Files Count: \(viewModel.files.count)")
if viewModel.files.isEmpty {
Text("Folder doesn't exist or is empty")
.foregroundColor(.red)
} else {
List(files, id: \.self) { fileURL in
Button(action: {
do {
selectedFileContent = String(try String(contentsOf: fileURL).prefix(10_000))
showAlert = true
} catch {
print("Error reading file: \(error)")
}
}) {
List(viewModel.files, id: \.self) { fileURL in
Button(action: viewModel.showFile(fileURL: fileURL)) {
Text(fileURL.lastPathComponent)
}
}
}
}
.onAppear(perform: loadFiles)
.alert(isPresented: $showAlert) {
Alert(title: Text("File Content"), message: Text(selectedFileContent), dismissButton: .default(Text("Close")))
.alert(isPresented: $viewModel.showAlert) {
Alert(title: Text("File Content"), message: Text(viewModel.selectedFileContent), dismissButton: .default(Text("Close")))
}
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button("Close") {
presentationMode.wrappedValue.dismiss()
dismiss()
}
}
}
}
}

func loadFiles() {
let fileManager = FileManager.default

do {
let fileURLs = try fileManager.contentsOfDirectory(at: localURL, includingPropertiesForKeys: nil)

files = fileURLs.sorted(by: { $0.lastPathComponent < $1.lastPathComponent })
} catch {
print("Error loading files: \(error)")
}
}
}

@available(iOS 16.0, *)
struct FileBrowserView_Previews: PreviewProvider {
static var previews: some View {
FileBrowserView(localURL: URL(string: NSTemporaryDirectory())!)
FileBrowserView(viewModel: FileBrowserViewModel(localURL: nil))
}
}
Loading
Loading