Upload multiple images to Google Drive using API/SDK (IOS, Swift) - ios

I am developing an App that will ask for 5 images, assign them to the proper UIImageViewer for preview purposes, and then I would like to hit upload and all 5 images go to a team drive. At this point all of it works except the code snippet I have is only able to upload images if they are in the App's Documents Directory. I would like to reference back to the 5 previously chosen images and upload them to a team drive but I do not know how to go about that.
Each button has been assigned a tag number, in which will equal their designated UIImageViewer. I am trying to reference the other previously chosen images but an error says in the 'UploadAction' button "Cannot convert value of type 'UIImage' to expected argument type 'String'". Here is my code, any help would be greatly appreciated!! (This is in Swift in Xcode, I could not find any examples using swift to upload pictures using a phone camera or photo gallery)
import UIKit
import GoogleSignIn
import GoogleAPIClientForREST
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, GIDSignInUIDelegate, UIPickerViewDelegate, UITextFieldDelegate{
// func numberOfComponents(in pickerView: UIPickerView) -> Int {
//
// }
// func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
//
// }
#IBOutlet weak var imageView1: UIImageView!
#IBOutlet weak var imageView2: UIImageView!
#IBOutlet weak var imageView3: UIImageView!
#IBOutlet weak var imageView4: UIImageView!
#IBOutlet weak var imageView5: UIImageView!
#IBOutlet weak var resultsLabel: UILabel!
var imagePicker = UIImagePickerController()
var imagePicked = 0
var cameraPicker = UIImagePickerController()
var cameraPicked = 0
fileprivate let service = GTLRDriveService()
private var drive: ATGoogleDrive?
override func viewDidLoad() {
super.viewDidLoad()
cameraPicker.delegate = self
cameraPicker.sourceType = .camera
cameraPicker.allowsEditing = false; imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = false;
GIDSignIn.sharedInstance().uiDelegate = self;
self.view.backgroundColor = UIColor.lightGray;
setupGoogleSignIn()
drive = ATGoogleDrive(service)
}
#IBAction func openCamera(_ sender: UIButton){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
cameraPicked = sender.tag
present(cameraPicker, animated: true)
}
}
#IBAction func chooseImage1(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.savedPhotosAlbum){
imagePicked = sender.tag
present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
let cameraImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
if imagePicked == 1 {
imageView1.image = pickedImage
} else if imagePicked == 2 {
imageView2.image = pickedImage
} else if imagePicked == 3 {
imageView3.image = pickedImage
} else if imagePicked == 4 {
imageView4.image = pickedImage
} else if imagePicked == 5 {
imageView5.image = pickedImage
} else if cameraPicked == 6 {
imageView1.image = cameraImage
} else if cameraPicked == 7 {
imageView2.image = cameraImage
} else if cameraPicked == 8 {
imageView3.image = cameraImage
} else if cameraPicked == 9 {
imageView4.image = cameraImage
} else if cameraPicked == 10 {
imageView5.image = cameraImage
}
dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true)
}
private func setupGoogleSignIn() {
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().scopes = [kGTLRAuthScopeDriveFile]
GIDSignIn.sharedInstance().signInSilently()
}
// MARK: - Actions
**#IBAction func uploadAction(_ sender: Any) {
if let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let uploadem = imageView1.image
drive?.uploadFile("agostini_tech_demo", filePath: uploadem, MIMEType: "image/png") { (fileID, error) in
print("Upload file ID: \(fileID); Error: \(error?.localizedDescription)")**
}
}
}
#IBAction func listAction(_ sender: Any) {
drive?.listFilesInFolder("agostini_tech_demo") { (files, error) in
guard let fileList = files else {
print("Error listing files: \(error?.localizedDescription)")
return
}
self.resultsLabel.text = fileList.files?.description
}
}
}
// MARK: - GIDSignInDelegate
extension ViewController: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let _ = error {
// service.authorizer = nil
} else {
// service.authorizer = user.authentication.fetcherAuthorizer()
}
}
}

Related

I get "boringssl" error when uploading image to Firebase for iOS

I'm simply trying to upload an image but I'm getting this error "[boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed to log metrics
Optional("User does not have permission to access 'here was the link to the folder.' ")"
My goal is to upload a photo and access it later from another page, but now I'm getting this error.
edit: Later I realized that I am getting some of the same error while signing up "[boringssl] boringssl_metrics_log_metric_block_invoke(153)".
The entered user can register and appears in the Firebase interface, but the above error is displayed on the console.
import UIKit
import Firebase
class UploadViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var commentText: UITextField!
#IBOutlet weak var uploadVar: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
imageView.isUserInteractionEnabled = true
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(chooseImage))
imageView.addGestureRecognizer(gestureRecognizer)
}
#IBAction func UploadClicked(_ sender: Any) {
let storage = Storage.storage()
let storageReferance = storage.reference()
let mediaFolder = storageReferance.child("media")
if let data = imageView.image?.jpegData(compressionQuality: 0.5) {
let imageReferance = mediaFolder.child("image.jpg")
imageReferance.putData(data, metadata: nil) { metaData, error in
if error != nil {
print(error?.localizedDescription)
} else {
imageReferance.downloadURL { url, error in
if error == nil {
let imageURL = url?.absoluteString
print(imageURL)
}
}
}
}
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
imageView.image = info[.originalImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
#objc func chooseImage() {
let pickerController = UIImagePickerController()
pickerController.delegate = self
pickerController.sourceType = .photoLibrary
present(pickerController, animated: true, completion: nil)
}
}

Getting error `Do you want to add protocol stubs? [duplicate]

This question already has answers here:
Xcode 8 says "Do you want to add a stub?" How do I answer?
(3 answers)
Closed 4 years ago.
I added the ImageView Protocol. What can be done to remove the error
Do you want to add protocol stubs?
CardsViewController
import UIKit
protocol ImageViewProtocol{
func sendImageToViewController(theImage: UIImage)
}
class CardsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImageViewProtocol {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var locationTextField: UITextField!
#IBOutlet weak var imageView: UIImageView!
#IBAction func goToViewController2Action(_ sender: Any)
{
let viewcontroller2 = storyboard?.instantiateViewController(withIdentifier: "viewController2") as! ViewController2
viewcontroller2.delegate = self
self.navigationController?.pushViewController(viewcontroller2, animated: true)
}
func chooseImagePickerAction(source: UIImagePickerController.SourceType) {
if UIImagePickerController.isSourceTypeAvailable(source) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = source
self.present(imagePicker, animated: true, completion: nil)
}
}
#IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
if nameTextField.text == "" || locationTextField.text == "" || textField.text == "" {
print("Not all fields are filled")
} else {
if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext {
let card = Card(context: context)
card.name = nameTextField.text
card.location = locationTextField.text
card.number = textField.text
if let image = imageView.image {
card.image = image.pngData()
}
do {
try context.save()
print("Cохранение удалось!")
} catch let error as NSError {
print("Не удалось сохранить данные \(error), \(error.userInfo)")
}
}
performSegue(withIdentifier: "unwindSegueFromNewCard", sender: self)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
imageView.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
}
ViewController2
import UIKit
class ViewController2: UIViewController {
var filter : CIFilter!
var delegate: ImageViewProtocol!
#IBOutlet weak var select: UISegmentedControl!
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var barcodeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
barcodeImageView.image = UIImage(named: "photo")
}
#IBAction func saveButtonAction(_ sender: Any) {
if textField.text == "" {
print("Not all fields are filled")
} else {
delegate.sendImageToViewController(theImage: barcodeImageView.image!)
self.navigationController?.popViewController(animated: true)
}
performSegue(withIdentifier: "unwindSegueFromViewController", sender: sender)
}
#IBAction func tappedEnter(_ sender: Any) {
if textField.text?.isEmpty ?? true {
return
} else {
if let texttxt = textField.text {
let data = texttxt.data(using: .ascii, allowLossyConversion: false)
if select.selectedSegmentIndex == 0
{
filter = CIFilter(name: "CICode128BarcodeGenerator")
} else {
filter = CIFilter(name: "CIQRCodeGenerator")
}
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 5, y: 5)
let image = UIImage(ciImage: filter.outputImage!.transformed(by: transform))
barcodeImageView.image = image
}
}
}
}
This error comes because you implemented protocol (ImageViewProtcol) but you haven't add required methods of your protocol (in your case sendImageToViewController(theImage: UIImage)). All methods of your protocol are required by default. If you want to change it, you can look here.
It's the same as when you're implementing UITableViewDataSource, you also need to add required methods like number of items etc.
To fix this, add this method to your CardsViewController:
func sendImageToViewController(theImage: UIImage) {
// do something with image
}

Issues Uploading Images and posts to Firebase 5 Database

I am currently trying to upload a photo URL and post caption onto my firebase database. The photos are currently being saved on firebase storage which is fine, however I would like for it to also appear on the firebase database.
I repeatedly find myself dealing with this error "Value of type 'StorageMetadata' has no member 'downloadURL'"
I understand that in firebase 5 to get the url from storage you need to call downloadURL on storage reference, not metadata. I have tried multiple ways and examples, but it all leads to errors.screenshot of error
#IBOutlet weak var photo: UIImageView!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var removeButton: UIBarButtonItem!
#IBOutlet weak var shareButton: UIButton!
var selectedImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleSelectPhoto)); photo.addGestureRecognizer(tapGesture)
photo.isUserInteractionEnabled = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
handlePost()
}
func handlePost() {
if selectedImage != nil {
self.shareButton.isEnabled = true
self.removeButton.isEnabled = true
self.shareButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
}else{
self.shareButton.isEnabled = false
self.shareButton.backgroundColor = .lightGray
self.removeButton.isEnabled = false
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
#objc func handleSelectPhoto() {
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
#IBAction func shareButton_TouchUpInside(_ sender: Any) {
view.endEditing(true)
let hud = JGProgressHUD(style: .dark)
hud.textLabel.text = "Loading"
hud.show(in: self.view)
hud.dismiss(afterDelay: 3.0)
if let profileImg = self.selectedImage, let imageData = UIImageJPEGRepresentation(profileImg, 0.1) {
let photoIdString = NSUUID().uuidString
let storageRef = Storage.storage().reference(forURL: ".......").child("posts").child(photoIdString)
storageRef.putData(imageData, metadata: nil, completion: { (metadata, error) in
if error != nil {
return
}
//let photoUrl = url?.absoluteString
let photoUrl = metadata?.downloadURL()?.absoluteString
self.sendDataToDatabase(photoUrl: photoUrl!)
}
)}
}
#IBAction func remove_TouchUpInside(_ sender: Any) {
clean()
handlePost()
}
func sendDataToDatabase(photoUrl: String) {
let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newPostId = postsReference.childByAutoId().key
let newPostReference = postsReference.child(newPostId)
newPostReference.setValue(["photoUrl": photoUrl, "caption": captionTextView.text!], withCompletionBlock: {
(error, ref) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
ProgressHUD.showSuccess("Success")
self.clean()
self.tabBarController?.selectedIndex = 0 // switches user back to selected tabbar 0 = first 1 = second etc.
})
}
func clean() {
self.captionTextView.text = ""
self.photo.image = UIImage(named:"placeholder-photo")
self.selectedImage = nil
}
}
extension CameraViewController: UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
print("did finish picking media")
if let image = info["UIImagePickerControllerOriginalImage"]
as? UIImage {
selectedImage = image
photo.image = image
}
// profileImage.image = infoPhoto
dismiss(animated: true, completion: nil)
}
}
import UIKit
import ProgressHUD
import FirebaseStorage
import FirebaseDatabase
class CameraViewController: UIViewController {
#IBOutlet weak var photo: UIImageView!
#IBOutlet weak var shareButton: UIButton!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var removeButton: UIBarButtonItem!
var selectedImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleSelectPhoto))
photo.addGestureRecognizer(tapGesture)
photo.isUserInteractionEnabled = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
handlePost()
}
func handlePost(){
if selectedImage != nil {
self.shareButton.isEnabled = true
self.removeButton.isEnabled = true
self.shareButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
} else {
self.shareButton.isEnabled = false
self.removeButton.isEnabled = false
self.shareButton.backgroundColor = .lightGray
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
#objc func handleSelectPhoto(){
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
// Share photos to the storage database
#IBAction func shareButton_TouchUpInside(_ sender: Any) {
view.endEditing(true)
ProgressHUD.show("Please wait...", interaction: false)
if let profileImg = self.selectedImage, let photoData = profileImg.jpegData(compressionQuality: 0.1) {
let photoIdString = NSUUID().uuidString
print(photoIdString)
let storageRef = Storage.storage().reference(forURL:Config.STORAGE_ROOT_REF).child("Posts").child(photoIdString)
storageRef.putData(photoData, metadata: nil, completion: { (metadata, error) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
let photoUrl = metadata?.downloadURL()?.absoluteString
self.sendDataToDatabase(photoUrl: photoUrl!)
})
} else {
ProgressHUD.showError("Profile image can't be empty")
}
}
#IBAction func remove_touchUpInside(_ sender: Any) {
clean()
handlePost()
}
func sendDataToDatabase(photoUrl:String){
let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newPostId = postsReference.childByAutoId().key
let newPostReference = postsReference.child(newPostId)
newPostReference.setValue(["photoUrl": photoUrl, "caption": captionTextView.text!], withCompletionBlock: {
(error, ref) in
if error != nil{
ProgressHUD.showError(error!.localizedDescription)
return
}
ProgressHUD.showSuccess("Success")
self.clean()
self.tabBarController?.selectedIndex = 0
})
}
func clean(){
self.captionTextView.text = ""
self.photo.image = UIImage(named: "placeholder-img")
self.shareButton = nil
}
}
extension CameraViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("did Finish picking media")
if let chosenImage = info[.originalImage] as? UIImage {
selectedImage = chosenImage
photo.image = chosenImage
}
dismiss(animated: true, completion: nil)
}
}
Use Above code, it will successfully upload the image and post that to the Firebase Database

"Array index out of range" when choosing photos in Swift

I cant figure out what's the problem here.
I have 6 images and when i click on them it popsup a image picker. If i choose a photo with a sequence, like 1,2,3,4,5,6... it works. But when i choose the first photo that's not the first one (array[0]), i get an error:
`$"Array index out of range"
Here is my code:
class SecondViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagemEscolhida = -1
#IBOutlet var firstImageView: UIImageView!
#IBOutlet var secondImageView: UIImageView!
#IBOutlet var thirdImageView: UIImageView!
#IBOutlet var fourthImageView: UIImageView!
#IBOutlet var fifthImageView: UIImageView!
#IBOutlet var sixthImageView: UIImageView!
#IBAction func firstImageButton(sender: AnyObject) {
imagemEscolhida = 1
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func secondImageButton(sender: AnyObject) {
imagemEscolhida = 2
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func thirdImageButton(sender: AnyObject) {
imagemEscolhida = 3
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func fourthImageButton(sender: AnyObject) {
imagemEscolhida = 4
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func fifthImageButton(sender: AnyObject) {
imagemEscolhida = 5
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func sixthImageButton(sender: AnyObject) {
imagemEscolhida = 6
abreBibliotecaFotos(imagemEscolhida)
}
func abreBibliotecaFotos (img: Int )
{
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
let imagePicker = UIImagePickerController()
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
firstImageView.contentMode = .ScaleAspectFit
restaurante.imagem.insert(pickedImage, atIndex: imagemEscolhida-1)
switch imagemEscolhida
{
case 1:
firstImageView.image = restaurante.imagem[0]
case 2:
secondImageView.image = restaurante.imagem[1]
case 3:
thirdImageView.image = restaurante.imagem[2]
case 4:
fourthImageView.image = restaurante.imagem[3]
case 5:
fifthImageView.image = restaurante.imagem[4]
case 6:
sixthImageView.image = restaurante.imagem[5]
default:
println("Something else")
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
}
You should initialize the array before you use it in the correct size. I would like to refer to my answer to a really similar question.
So initialize it from 0 to 5 at definition then your code should work.
It looks like the restaurante.imagem array is empty and your code crashes because you try to insert something at index which is higher than the maximum index of the array - which is 0.
The line to blame is:
restaurante.imagem.insert(pickedImage, atIndex: imagemEscolhida-1)

UIImage not saving to Camera Roll

I'm currently writing a photo app for iOS in Swift. I'm using the CoreImage Framework to generate a pixel effect on a UIImageView selected by the user. However, I'm having trouble saving the "pixeled" image to the iPhone's Camera Roll. Normally I use
UIImageWriteToSavedPhotosAlbum(pixeledImage,nil,nil,nil)
but it's not saving the UIImage. I have given the app full access to the photo library on the device. It will be helpful if someone could help me figure this out. My image picker:
class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
var imagetobepassed: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func Cameratapped(sender: AnyObject) {
var camera = UIImagePickerController()
dispatch_async(dispatch_get_main_queue()) {
camera.delegate = self
camera.sourceType = UIImagePickerControllerSourceType.Camera
camera.allowsEditing = false
self.presentViewController(camera, animated: true, completion: nil)
}
}
#IBAction func photolib(sender: AnyObject) {
var photo = UIImagePickerController()
dispatch_async(dispatch_get_main_queue()) {
photo.delegate = self
photo.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
photo.allowsEditing = false
self.presentViewController(photo, animated: true, completion: nil)
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
imagetobepassed = image
self.dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func editorPressed(sender: AnyObject) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "image" {
var editorview = segue.destinationViewController as! EditorViewController
editorview.imagerecived = imagetobepassed
}
}
}
And my editor:
import UIKit
class EditorViewController: UIViewController {
var imagerecived:UIImage!
var pixeledImage:UIImage!
var savedImage:UIImage!
#IBOutlet var imageview: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
pixel()
}
// this function will prduce the pixel effect
func pixel() {
var regularImage = CIImage(image: imagerecived)
var filter = CIFilter(name: "CIPixellate")
filter.setDefaults()
filter.setValue(regularImage, forKey: kCIInputImageKey)
var output = filter.outputImage
pixeledImage = UIImage(CIImage: output)
imageview.image = pixeledImage
}
#IBAction func SaveTapped(sender: AnyObject) {
println(pixeledImage)
UIImageWriteToSavedPhotosAlbum(pixeledImage,nil,nil,nil) // not saving image
}
How can I make this work? I do see this error:
2015-05-16 23:40:05.416 Pixelate2[21579:3341726] Connection to assetsd
was interrupted or assetsd died
First use this line to save image:-
UIImageWriteToSavedPhotosAlbum(pixeledImage, self, "image:didFinishSavingWithError:contextInfo:", nil)
Now implement this method,to catch the error you are getting:-
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if error == nil {
}
else
{
//log the error out here ,if any
}
}
There is another work around, if you are getting memory warning !
ALAssetsLibrary* lib = [[ALAssetsLibrary alloc] init];
[lib writeImageDataToSavedPhotosAlbum:imageData metadata:nil
completionBlock:^(NSURL *assetURL, NSError *error)
{
// do whatever in the completion handler
}];
I was able to solve the issue using this code:
#IBAction func SaveTapped(sender: AnyObject) {
let softwareContext = CIContext(options: [kCIContextUseSoftwareRenderer:true])
let cgimg = softwareContext.createCGImage(savedImage,
fromRect: savedImage.extent())
let libary = ALAssetsLibrary()
libary.writeImageToSavedPhotosAlbum(cgimg, metadata: savedImage.properties(),
completionBlock: nil)
}

Resources