Impressia/VernissageShare/ComposeView.swift

67 lines
2.2 KiB
Swift
Raw Normal View History

2023-04-07 13:20:37 +02:00
//
// https://mczachurski.dev
// Copyright © 2023 Marcin Czachurski and the repository contributors.
// Licensed under the Apache License 2.0.
//
import Foundation
import SwiftUI
2023-04-07 14:20:12 +02:00
import PhotosUI
import PixelfedKit
import ClientKit
2023-04-07 18:58:15 +02:00
import EnvironmentKit
import WidgetsKit
import ServicesKit
2023-04-07 13:20:37 +02:00
struct ComposeView: View {
2023-04-07 14:20:12 +02:00
@EnvironmentObject var client: Client
2023-04-07 13:20:37 +02:00
private let attachments: [NSItemProvider]
2023-04-07 13:20:37 +02:00
2023-04-07 18:58:15 +02:00
public init(attachments: [NSItemProvider]) {
self.attachments = attachments
2023-04-07 13:20:37 +02:00
}
var body: some View {
2023-04-07 18:58:15 +02:00
NavigationView {
BaseComposeView(attachments: self.attachments) {
NotificationCenter.default.post(name: NotificationsName.shareSheetClose, object: nil)
} onUpload: { photoAttachment in
await self.upload(photoAttachment)
2023-04-07 18:58:15 +02:00
}
.navigationTitle("compose.navigationBar.title")
.navigationBarTitleDisplayMode(.inline)
2023-04-07 13:20:37 +02:00
}
}
private func upload(_ photoAttachment: PhotoAttachment) async {
do {
// Image shouldn't be uploaded yet.
guard photoAttachment.uploadedAttachment == nil else {
2023-04-07 13:20:37 +02:00
return
}
// From extension we are sending already resized file.
guard let data = photoAttachment.photoData,
let uiImage = UIImage(data: data) else {
2023-04-07 13:20:37 +02:00
return
}
// Compresing to JPEG with extendedRGB color space.
guard let data = uiImage.getJpegData() else {
2023-04-07 13:20:37 +02:00
return
}
let fileIndex = String.randomString(length: 8)
if let mediaAttachment = try await self.client.media?.upload(data: data,
fileName: "file-\(fileIndex).jpg",
mimeType: "image/jpeg") {
photoAttachment.uploadedAttachment = mediaAttachment
}
} catch {
photoAttachment.uploadError = error
2023-04-07 13:20:37 +02:00
ErrorService.shared.handle(error, message: "compose.error.postingPhotoFailed", showToastr: true)
}
}
}