Site blog title mreza

UPLOAD IMAGE FROM SWIFT 3 IOS APP TO RAILS 5 SERVER

30/12/2016
Railsios

Once upon a time I was given the task to send an image captured on IOS to our Rails back-end server and at first I figured: “Wow this can’t be such a big deal, I know how to take an image and I know how to make a request so why would this be any different from a normal request. Why would an image be special?”. Well, turns out I was kind of wrong. The thing about sending a picture is you are actually not sending a picture. Well, you are but not formatted as an actual picture. Yes, I was confused about it as well, but that’s how computers work. Crazy, right? First you have to encode the picture into code computer-readable code, then you send that code to your server, then you decode that code into a picture again and Voila there is your picture – that’s all, simple as that 😀 It sounds easy and at the end of the day it actually is. I will show you some code and if you want to test it out, I’ve also prepared some convenient templates that you can pull from my repo to immediately put into use: IOS camera template Rails template

So lets start:

First we do some safe unwrapping so we avoid possible crashes in our app. In case UIImageView doesn't have an image, then we return the data for the specified image in PNG format (imageData variable), and the last thing we do is encode imageData to that code so that computers can understand, just as I said earlier. We do that inside of the encodedImageData variable. It's pretty straightforward:


  if let capturePhotoImage = self.capturePhotoView.image {
    if let imageData = UIImagePNGRepresentation(capturePhotoImage) {
      let encodedImageData = imageData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
    }
  }

Then we add a simple asynchronous post request with our encodedImageData as a parameter and we should decode that back to our beautiful image.


  if let capturePhotoImage = self.capturePhotoView.image {
    if let imageData = UIImagePNGRepresentation(capturePhotoImage) {
        let encodedImageData = imageData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
        var request = URLRequest(url: URL(string: "http://192.168.1.12:3000/create-image")!)
        request.httpMethod = "POST"
        let postString = "image=\(encodedImageData)"
        request.httpBody = postString.data(using: .utf8)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print("error=\(error)")
                return
            }
            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }
            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString)")
        }
        task.resume()
    }
  }

And now for the server side. To be perfectly honest with you guys, this is the part where I encountered problems. It turned out that every decoded image was black. This kept troubling me for a couple of days. I kept eyeballing the project (eyeballing technique - when the developer is very desperate and is searching for a possible typo and suddenly realizes he hates computers) and then I realized there was an empty space where there should have been a ‘+’.

So first we create a new StringIO instance from the decoded image params (you can see here we're replacing the empty whitespace with the useful + sign), with the class we are creating class from image variable, with class_eval we are adding methods to image, and then giving our image name and content type. Finally we are create our image and save it to our database.


    def create_image
      image = StringIO.new(Base64.decode64(params[:image].tr(' ', '+')))
      image.class.class_eval { attr_accessor :original_filename, :content_type }
      image.original_filename = SecureRandom.hex + '.png'
      image.content_type = 'image/png'

      create_image = Image.new(image: image)
      create_image.save!
    end

Category: Rails, iOS
OTHER POSTS
OTHER POSTS
Created with Sketch.
Omniauth f1d5b77f6e5fc9adc96fdb4dc3a7d5f3 %281%29
06/06/2018 / Krešimir Bojčić

DEVISE WITH OMNIAUTH FOR SINGLE AND MULTIPLE MODELS – RAILS 5

In this post we'll describe on how to use OmniAuth in combination with Rails and Devise to support authentication of existing and new users without asking for email/password combinations.
Conferencecam group
29/06/2018 / Krešimir Bojčić

LOGITECH GROUP – REMOTE VIDEO CONFERENCING SYSTEM REVIEW

To have a successful remote agency/client relationship you need three main ingredients: 1. Trust 2. Effective communication 3. Delivering results
Created with Sketch.
Global infra 3.30.18.b559f46825615c1ae40f319d0c4d9139fea9c492
29/06/2018 / Krešimir Bojčić

SCALE FOR SPEED AND AVAILABILITY

In this post I'll go over various options for scaling your business web platform. We'll take a look at five different approaches. There is no wrong or right approach, it is just a matter of what aspects you want to emphasize and what you...
Created with Sketch.
Railsandreact
28/06/2018 / Matija Munjaković

SETTING UP REACT & RAILS HAS NEVER BEEN EASIER

Just a couple of days ago Beta 1 of Rails 5.1 got released, bringing with it a slew of new features. Most prominent among them being the inclusion of Webpack. For the uninitiated, Webpack serves as a bundling tool for your project’s Java...
Untitled
03/07/2018 / Krešimir Bojčić

FREE SSL ON AWS OPSWORKS RAILS APP

In this post I'll try and describe how to set up SSL for your Rails app. This solution is free and will automatically extend the certificate once the certificate runs its course.
Created with Sketch.
23 512
06/06/2018 / Tin Ilijaš

HOW TO DEACTIVATE USER – RAILS WITH DEVISE

Sometimes when I find the time (which happens roughly 23 to 37 times each and every day) I visit Stack Overflow, hopefully to solve a problem – but regularly leave irritated and heartbroken because the solution is too geeky and doesn’t e...
Created with Sketch.
7e6dcc68 1ba3 11e7 8286 407dd1a1b50f
29/06/2018 / Tin Ilijaš

SWITCH USERS WITH USERSWITCH

Recently we were hired by a startup and quickly assigned a task to build a brand new feature for them. So no problemo here! The feature was fairly extensive which necessitated thorough testing – perhaps a third of the entire application ...
Untitled
03/07/2018 / Krešimir Bojčić

HOW TO BUILD AN MVP

So, you’ve decided to build a new disruptive product that will earn you glory and money? Congratulations… welcome to the club and good luck!
Created with Sketch.
1 ee4irlninahubiurfqv3fq
29/06/2018 / Tin Ilijaš

8 TIPS TO BECOME A DEVELOPER

Almost a year has flown by ever since I started learning programming from scratch. As a result of that, I am writing this blog post to help new and old developers with some tips I learned in this beautiful world of programming.
Created with Sketch.
Untitled
03/07/2018 / Krešimir Bojčić

VISUALIZE DATABASE SCHEMA – POSTGRESQL DB – RAILS 5

When working on bigger systems it helps having your database model visualized. There are many great solutions but a few of them are free. If you fit in the “small enough” not to use [ER/Studio Data Architect](https://www.idera.com/er-...
Helpprotectcompanydata large
29/06/2018 / Krešimir Bojčić

PROTECT THE DATA!

If you were to ask yourself – what is the essence of any software system – what would you say? (that is, what would you have said without having read the title of this post 😃).
Created with Sketch.
Hmawawbapi
03/07/2018 / Matija Munjaković

HANDLING MOBILE AUTHENTICATION WITH A WEB-BASED API

Quite recently I had the chance of implementing a log-in/authentication system for one of our mobile applications. Resources available for both the Android and iOS eco-systems are fairly exhaustive but comparisons of the pros and cons of...
Created with Sketch.
Omniauth f1d5b77f6e5fc9adc96fdb4dc3a7d5f3 %281%29
06/06/2018 / Krešimir Bojčić

DEVISE WITH OMNIAUTH FOR SINGLE AND MULTIPLE MODELS – RAILS 5

In this post we'll describe on how to use OmniAuth in combination with Rails and Devise to support authentication of existing and new users without asking for email/password combinations.
Created with Sketch.
Conferencecam group
29/06/2018 / Krešimir Bojčić

LOGITECH GROUP – REMOTE VIDEO CONFERENCING SYSTEM REVIEW

To have a successful remote agency/client relationship you need three main ingredients: 1. Trust 2. Effective communication 3. Delivering results
Created with Sketch.
Global infra 3.30.18.b559f46825615c1ae40f319d0c4d9139fea9c492
29/06/2018 / Krešimir Bojčić

SCALE FOR SPEED AND AVAILABILITY

In this post I'll go over various options for scaling your business web platform. We'll take a look at five different approaches. There is no wrong or right approach, it is just a matter of what as...
Created with Sketch.
Railsandreact
28/06/2018 / Matija Munjaković

SETTING UP REACT & RAILS HAS NEVER BEEN EASIER

Just a couple of days ago Beta 1 of Rails 5.1 got released, bringing with it a slew of new features. Most prominent among them being the inclusion of Webpack. For the uninitiated, Webpack serves as...
Created with Sketch.
Untitled
03/07/2018 / Krešimir Bojčić

FREE SSL ON AWS OPSWORKS RAILS APP

In this post I'll try and describe how to set up SSL for your Rails app. This solution is free and will automatically extend the certificate once the certificate runs its course.
Created with Sketch.
23 512
06/06/2018 / Tin Ilijaš

HOW TO DEACTIVATE USER – RAILS WITH DEVISE

Sometimes when I find the time (which happens roughly 23 to 37 times each and every day) I visit Stack Overflow, hopefully to solve a problem – but regularly leave irritated and heartbroken because...
Created with Sketch.
7e6dcc68 1ba3 11e7 8286 407dd1a1b50f
29/06/2018 / Tin Ilijaš

SWITCH USERS WITH USERSWITCH

Recently we were hired by a startup and quickly assigned a task to build a brand new feature for them. So no problemo here! The feature was fairly extensive which necessitated thorough testing – pe...
Created with Sketch.
Untitled
03/07/2018 / Krešimir Bojčić

HOW TO BUILD AN MVP

So, you’ve decided to build a new disruptive product that will earn you glory and money? Congratulations… welcome to the club and good luck!
Created with Sketch.
1 ee4irlninahubiurfqv3fq
29/06/2018 / Tin Ilijaš

8 TIPS TO BECOME A DEVELOPER

Almost a year has flown by ever since I started learning programming from scratch. As a result of that, I am writing this blog post to help new and old developers with some tips I learned in this b...
Created with Sketch.
Untitled
03/07/2018 / Krešimir Bojčić

VISUALIZE DATABASE SCHEMA – POSTGRESQL DB – RAILS 5

When working on bigger systems it helps having your database model visualized. There are many great solutions but a few of them are free. If you fit in the “small enough” not to use [ER/Studio D...
Created with Sketch.
Helpprotectcompanydata large
29/06/2018 / Krešimir Bojčić

PROTECT THE DATA!

If you were to ask yourself – what is the essence of any software system – what would you say? (that is, what would you have said without having read the title of this post 😃).
Created with Sketch.
Hmawawbapi
03/07/2018 / Matija Munjaković

HANDLING MOBILE AUTHENTICATION WITH A WEB-BASED API

Quite recently I had the chance of implementing a log-in/authentication system for one of our mobile applications. Resources available for both the Android and iOS eco-systems are fairly exhaustive...
Created with Sketch. Created with Sketch.
Omniauth f1d5b77f6e5fc9adc96fdb4dc3a7d5f3 %281%29
06/06/2018 / Krešimir Bojčić

DEVISE WITH OMNIAUTH FOR SINGLE AND MULTIPLE MODELS – RAILS 5

In this post we'll describe on how to use OmniAuth in combination with Rails and Devise to support authentication of existing a...
Created with Sketch. Created with Sketch.
Conferencecam group
29/06/2018 / Krešimir Bojčić

LOGITECH GROUP – REMOTE VIDEO CONFERENCING SYSTEM REVIEW

To have a successful remote agency/client relationship you need three main ingredients: 1. Trust 2. Effective communication...
Created with Sketch. Created with Sketch.
Global infra 3.30.18.b559f46825615c1ae40f319d0c4d9139fea9c492
29/06/2018 / Krešimir Bojčić

SCALE FOR SPEED AND AVAILABILITY

In this post I'll go over various options for scaling your business web platform. We'll take a look at five different approache...
Created with Sketch. Created with Sketch.
Railsandreact
28/06/2018 / Matija Munjaković

SETTING UP REACT & RAILS HAS NEVER BEEN EASIER

Just a couple of days ago Beta 1 of Rails 5.1 got released, bringing with it a slew of new features. Most prominent among them ...
Created with Sketch. Created with Sketch.
Untitled
03/07/2018 / Krešimir Bojčić

FREE SSL ON AWS OPSWORKS RAILS APP

In this post I'll try and describe how to set up SSL for your Rails app. This solution is free and will automatically extend th...
Created with Sketch. Created with Sketch.
23 512
06/06/2018 / Tin Ilijaš

HOW TO DEACTIVATE USER – RAILS WITH DEVISE

Sometimes when I find the time (which happens roughly 23 to 37 times each and every day) I visit Stack Overflow, hopefully to s...
Created with Sketch. Created with Sketch.
7e6dcc68 1ba3 11e7 8286 407dd1a1b50f
29/06/2018 / Tin Ilijaš

SWITCH USERS WITH USERSWITCH

Recently we were hired by a startup and quickly assigned a task to build a brand new feature for them. So no problemo here! The...
Created with Sketch. Created with Sketch.
Untitled
03/07/2018 / Krešimir Bojčić

HOW TO BUILD AN MVP

So, you’ve decided to build a new disruptive product that will earn you glory and money? Congratulations… welcome to the clu...
Created with Sketch. Created with Sketch.
1 ee4irlninahubiurfqv3fq
29/06/2018 / Tin Ilijaš

8 TIPS TO BECOME A DEVELOPER

Almost a year has flown by ever since I started learning programming from scratch. As a result of that, I am writing this blog ...
Created with Sketch. Created with Sketch.
Untitled
03/07/2018 / Krešimir Bojčić

VISUALIZE DATABASE SCHEMA – POSTGRESQL DB – RAILS 5

When working on bigger systems it helps having your database model visualized. There are many great solutions but a few of them...
Created with Sketch. Created with Sketch.
Helpprotectcompanydata large
29/06/2018 / Krešimir Bojčić

PROTECT THE DATA!

If you were to ask yourself – what is the essence of any software system – what would you say? (that is, what would you have sa...
Created with Sketch. Created with Sketch.
Hmawawbapi
03/07/2018 / Matija Munjaković

HANDLING MOBILE AUTHENTICATION WITH A WEB-BASED API

Quite recently I had the chance of implementing a log-in/authentication system for one of our mobile applications. Resources av...