[ad_1]
I’ve a query about tips on how to save simply taken picture to the server.
I already created a View with the digital camera (you may open it and take an image and saved it to your digital camera roll) and the second View (the place you may add pictures from the digital camera roll to the server)
However how I can join them?
My code
Select picture from the libruary:
PictureView
import SwiftUI
struct PictureView: View {
// present picture picker
@State var showImagePicker: Bool = false
// present chosen picture
@State var selectedImage: Picture? = Picture("")
var physique: some View {
VStack {
// create button to pick out picture
Button(motion: {
self.showImagePicker.toggle()
}, label: {
Textual content("Choose picture")
})
// present picture
self.selectedImage?.resizable().scaledToFit()
// present button to add picture
Button(motion: {
// convert picture into base 64
let uiImage: UIImage = self.selectedImage.asUIImage()
let imageData: Information = uiImage.jpegData(compressionQuality: 0.1) ?? Information()
let imageStr: String = imageData.base64EncodedString()
// ship request to server
guard let url: URL = URL(string:
"gs://lalala-af09c.appspot.com/swiftui-save-image.php") else {
print("invalid URL")
return
}
// create parameters
let paramStr: String = "picture=(imageStr)"
let paramData: Information = paramStr.knowledge(utilizing: .utf8) ?? Information()
var urlRequest: URLRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = paramData
// required for sending massive knowledge
urlRequest.setValue("software/x-www-form-urlencoded", forHTTPHeaderField: "Content material-Kind")
// ship the request
URLSession.shared.dataTask(with: urlRequest, completionHandler: { (knowledge, response, error) in
guard let knowledge = knowledge else {
print("invalid knowledge")
return
}
// present response in string
let responseStr: String = String(knowledge: knowledge, encoding: .utf8) ?? ""
print(responseStr)
})
.resume()
}, label: {
Textual content("Add picture")
})
}
.sheet(isPresented: $showImagePicker, content material: {
ImagePicker(picture: self.$selectedImage)
})
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
PictureView()
}
}
ImagePicker
import Basis
import SwiftUI
extension View {
public func asUIImage() -> UIImage {
let controller = UIHostingController(rootView: self)
controller.view.body = CGRect(x: 0, y: CGFloat(Int.max), width: 1, top: 1)
UIApplication.shared.home windows.first!.rootViewController?.view.addSubview(controller.view)
let measurement = controller.sizeThatFits(in: UIScreen.primary.bounds.measurement)
controller.view.bounds = CGRect(origin: .zero, measurement: measurement)
controller.view.sizeToFit()
// right here is the decision to the operate that converts UIView to UIImage: `.asImage()`
let picture = controller.view.asUIImage()
controller.view.removeFromSuperview()
return picture
}
}
extension UIView {
// That is the operate to transform UIView to UIImage
public func asUIImage() -> UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.picture { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}
struct ImagePicker: UIViewControllerRepresentable {
@Surroundings(.presentationMode)
var presentationMode
@Binding var picture: Picture?
class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@Binding var presentationMode: PresentationMode
@Binding var picture: Picture?
init(presentationMode: Binding<PresentationMode>, picture: Binding<Picture?>) {
_presentationMode = presentationMode
_image = picture
}
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo data: [UIImagePickerController.InfoKey : Any]) {
let uiImage = data[UIImagePickerController.InfoKey.originalImage] as! UIImage
picture = Picture(uiImage: uiImage)
presentationMode.dismiss()
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
presentationMode.dismiss()
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(presentationMode: presentationMode, picture: $picture)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<ImagePicker>) -> UIImagePickerController {
let picker = UIImagePickerController()
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: UIImagePickerController,
context: UIViewControllerRepresentableContext<ImagePicker>) {
}
}
And resolution to open digital camera is:
CameraView
import SwiftUI
import AVFoundation
struct CameraView: View {
@StateObject var digital camera = CameraModel()
var physique: some View {
ZStack{
// Shade.black
CameraPreview(digital camera: digital camera)
.ignoresSafeArea()
VStack{
if digital camera.isTaken{
HStack{
Spacer()
Button(motion: digital camera.reTake, label: {
Picture(systemName: "arrow.triangle.2.circlepath.digital camera")
.foregroundColor(.black)
.padding()
.background(Shade.white)
.clipShape(Circle())
}).padding(.trailing,10)
}
Spacer()
}
Spacer()
HStack{
if digital camera.isTaken{
Button(motion: {
if !digital camera.isSaved{
digital camera.savePic()
}
}, label: {
Textual content(digital camera.isSaved ? "Saved" : "Save")
.foregroundColor(.black)
.fontWeight(.semibold)
.padding(.vertical,10)
.padding(.horizontal,20)
.background(Shade.white)
.clipShape(Capsule())
}).padding(.main)
Spacer()
}else{
Button(motion: digital camera.takePic, label: {
ZStack{
Circle()
.fill(Shade.white)
.body(width: 65, top: 65, alignment: .middle)
Circle()
.stroke(Shade.white,lineWidth: 2)
.body(width: 75, top: 75, alignment: .middle)
}
})
}
}.body(top: 75)
}
}.onAppear(carry out: {
digital camera.examine()
}).alert(isPresented: $digital camera.alert){
Alert(title: Textual content("Allow digital camera"))
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
CameraView()
}
}
class CameraModel : NSObject, ObservableObject, AVCapturePhotoCaptureDelegate{
@Printed var isTaken = false
@Printed var session = AVCaptureSession()
@Printed var alert = false
@Printed var output = AVCapturePhotoOutput()
@Printed var preview : AVCaptureVideoPreviewLayer!
@Printed var isSaved=false
@Printed var picData = Information(depend:0)
func examine(){
change AVCaptureDevice.authorizationStatus(for: .video) {
case .licensed:
setUp()
return
case .notDetermined :
AVCaptureDevice.requestAccess(for: .video) { (standing) in
if standing{
self.setUp()
}
}
case .denied:
self.alert.toggle()
return
default:
return
}
}
func setUp(){
do{
self.session.beginConfiguration()
guard let system: AVCaptureDevice = AVCaptureDevice.default(.builtInWideAngleCamera,
for: .video, place: .again) else {
return
}
let enter = strive AVCaptureDeviceInput(system: system)
if self.session.canAddInput(enter){
print("enter taken")
self.session.addInput(enter)
}else{
print("enter not taken")
}
if self.session.canAddOutput(output){
print("output taken")
self.session.addOutput(output)
}
self.session.commitConfiguration()
}catch{
print(error.localizedDescription)
}
}
func takePic(){
self.output.capturePhoto(with: AVCapturePhotoSettings(), delegate: self)
DispatchQueue.international(qos: .background).async {
self.session.stopRunning()
DispatchQueue.primary.async {
withAnimation{
self.isTaken.toggle()
}
}
}
}
func reTake(){
DispatchQueue.international(qos: .background).async {
self.session.startRunning()
DispatchQueue.primary.async {
withAnimation{
self.isTaken.toggle()
}
self.isSaved=false
self.picData=Information(depend: 0)
}
}
}
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto picture: AVCapturePhoto, error: Error?) {
if error != nil{
return
}
print("image taken")
guard let imageData = picture.fileDataRepresentation() else {
return
}
self.picData = imageData
}
func savePic(){
guard let picture = UIImage(knowledge: self.picData) else{return}
//saving picture
UIImageWriteToSavedPhotosAlbum(picture, nil, nil, nil)
self.isSaved=true
print("pic saved")
}
}
struct CameraPreview : UIViewRepresentable{
@ObservedObject var digital camera : CameraModel
func makeUIView(context:Context) -> UIView {
let view = UIView(body:UIScreen.primary.bounds)
digital camera .preview = AVCaptureVideoPreviewLayer(session: digital camera.session)
digital camera.preview.body = view.body
digital camera.preview.videoGravity = .resizeAspectFill
view.layer.addSublayer(digital camera.preview)
self.digital camera.session.startRunning()
return view
}
func updateUIView(_ uiView: UIView, context: Context) {
}
}
Thanks very a lot
[ad_2]
