How to take a picture and save it to the app locally with swift

前端 未结 3 468
攒了一身酷
攒了一身酷 2021-01-31 12:43

I\'m working on an app where in the current stage when a user takes a picture the picture will be stored locally within the app.

 @IBAction func CameraAction(se         


        
3条回答
  •  逝去的感伤
    2021-01-31 13:31

    let fileDirectory : NSURL  = {
           return try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory , inDomain: .UserDomainMask , appropriateForURL: nil, create: true)
       }()
    
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        picker.dismissViewControllerAnimated(true, completion: nil)
    
        //save to album 
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
    
       //or to documents 
       //If you want to use png you have to change it later in saveImageToDocumentMethod in the guard statement
       saveImageToDocuments(image, filenameWithExtension: "test.jpg")
    }
    
    
    func saveImageToDocuments(image: UIImage, fileNameWithExtension: String){
    
           let imagePath = fileDirectory.URLByAppendingPathComponent("\(fileNameWithExtension)")
    
           guard let imageData = UIImageJPEGRepresentation(image, 1) else {
               // handle failed conversion
               print("jpg error")
               return
           }
           imageData.writeToFile((imagePath.path)!, atomically: true)
    
       }
    

    When you want to use that image all you need to do is use the imagePath again and convert it into a UIImage.

提交回复
热议问题