0
votes

I'm trying to upload an image from image view to Firebase storage.

The user will upload the image either from photo album or from camera to image view! What I want is to upload this image from image view to firebase storage.

I've tried to follow the example in the Firebase docs as here:

   let localFile: NSURL = ImageView.image


    let metadata = FIRStorageMetadata()
    metadata.contentType = "image/jpeg"

    // Upload file and metadata to the object 'images/mountains.jpg'
    let uploadTask = storage.child("images/DeviceImage.jpg").putFile(localFile, metadata: metadata);

    // Listen for state changes, errors, and completion of the upload.
    uploadTask.observeStatus(.Pause) { snapshot in
        // Upload paused
    }

    uploadTask.observeStatus(.Resume) { snapshot in
        // Upload resumed, also fires when the upload starts
    }

    uploadTask.observeStatus(.Progress) { snapshot in
        // Upload reported progress
        if let progress = snapshot.progress {
            let percentComplete = 100.0 * Double(progress.completedUnitCount) / Double(progress.totalUnitCount)
        }
    }

    uploadTask.observeStatus(.Success) { snapshot in
        // Upload completed successfully
    }

    // Errors only occur in the "Failure" case
    uploadTask.observeStatus(.Failure) { snapshot in
        guard let storageError = snapshot.error else { return }
        guard let errorCode = FIRStorageErrorCode(rawValue: storageError.code) else { return }
        switch errorCode {
        case .ObjectNotFound:
            // File doesn't exist

        case .Unauthorized:
            // User doesn't have permission to access file

        case .Cancelled:
            // User canceled the upload

            ...

        case .Unknown:
            // Unknown error occurred, inspect the server response
        }
    }

But I don't know how to convert the UIImageView into NSURL.

Here's the error I got: enter image description here

2
First ensure that the image exists on your disk, then create a NSURL from its path.Roecrew

2 Answers

3
votes

You'll need to convert the image to a file on disk and get the url of that to upload.

let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let filePath = "\(paths[0])/MyImageName.jpg"

// Save image.
UIImageJPEGRepresentation(image, 0.90)?.writeToFile(filePath, atomically: true)

See: How do I save a UIImage to a file?

Once it is written to disk you can get a url for the file like so:

let localFile = NSURL(fileURLWithPath: filePath)
0
votes

Instead of converting it to NSURL, you can get the PNG bytes of the selected image and upload it like this:

storage.reference().child("images/imageName.png").putData(selectedImage!.pngData()!, metadata: nil, completion: {_, error in
                guard error == nil else{
                    print("failed to upload image")
                    return
                }
            })