0

I am creating URL with NSURL based and then use NSURLSession to send a file to a REST API (self.prefix is a string like

/var/mobile/Applications/39FEBF47-6B74-48F2-8484-638D4B79A5FC/Documents/app/s7UqOoLJcI7tUCB/file.png).

let UUID: String = "'UUID:" + (randomStringWithLength(32) as String) + "' "

let ContentType: String =  "Content-Type:image/png < "

let str: String = "http://link/convert 'X-Auth-Token:a351sfddsf2cbcce8' 'X-Project-ID:2222' " + UUID + ContentType + self.prefix

let url = NSURL(string: str)
        let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
            print(NSString(data: data!, encoding: NSUTF8StringEncoding))
        }

task.resume()

I am getting

"fatal error: unexpectedly found nil while unwrapping an Optional value"

because URL is nil. What should I do to properly construct the URL to communicate with a REST API ?

This is how the interaction with the API looks in the command line:

http link:80/action 'X-Auth-Token:a3s33cfeffswffffs5454534bcce8' 'X-Project-ID:1234' 'UUID:abcdef123456' Content-Type:image/jpg < ~/Downloads/file.jpg

I currently create a HTTP request like below, but cannot see any response.

        self.currentImage.image = tempImage

        let body = NSMutableData()
        let boundary = generateBoundaryString()
        let fname = self.prefix
        let mimetype = "image/png"

        let imageData: NSData = UIImagePNGRepresentation(self.currentImage.image!)!


        let UUID: String = randomStringWithLength(12) as String
        let url = NSURL(string: "http://aaaa/bbb")!

        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.setValue("image/png", forHTTPHeaderField: "Content-Type")
        request.setValue("aa", forHTTPHeaderField: "X-Auth-Token")
        request.setValue("aaa", forHTTPHeaderField: "X-Project-ID")
        request.setValue(UUID, forHTTPHeaderField: "UUID")
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Disposition:form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

        body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
        body.appendData(imageData)
        body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


        body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)

        request.HTTPBody = body

        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request) { data, response, error in
            if let response = response, data = data {
                print(String(data: data, encoding: NSUTF8StringEncoding))
            }
        }


        task.resume()
4
  • Please show an example of what a valid URL would be. Your "in the command line" example would not be a valid URL. Commented May 25, 2016 at 9:49
  • @EricD The interaction with the url in the command line example is http (github.com/jkbrzt/httpie) and only then the url -- the url starts from link:80. So, for instance, abc/action 'X-Auth-Token:a3513cf345345345' 'X-Project-ID:845c3' 'UUID:abcdef123456' Content-Type:image/png< ~/Downloads/file.png Commented May 25, 2016 at 10:03
  • This is not an URL, this is a command line with parameters. Commented May 25, 2016 at 10:04
  • @EricD sth.com/action 'X-Auth-Token:a3513cfesdfsdfsdf' 'X-Project-ID:8413' 'UUID:ase56' Content-Type:image/png< ~/Downloads/file.png Commented May 25, 2016 at 10:13

1 Answer 1

1

A few things are wrong here I think...

1/ The url you have built there is not a url... What you are trying to build is a request with headers. Do this rather:

let url = NSURL(string: "http://link.com/convert")!

let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("image/png", forHTTPHeaderField: "Content-Type")
request.setValue("a351sfddsf2cbcce8", forHTTPHeaderField: "X-Auth_Token")
request.setValue("2222", forHTTPHeaderField: "X-Project-ID")

Then create the NSURLSession

let session = NSURLSession.sharedSession()

Then create the task

let task = session.dataTaskWithRequest(request) { data, response, error in
    if let response = response, data = data {
        print(String(data: data, encoding: NSUTF8StringEncoding))
    }
}

Then send it!

task.resume()

NOTE: I haven't added your self.prefix into the URL... You will probably need to put this in the request's payload or something... But this will solve your URL nil issues and is a neat way of doing a POST request to a REST API

Also

Your URL link http://link/convert is not valid

Sign up to request clarification or add additional context in comments.

7 Comments

I have a valid link. It is just stated it a simpler form.
Great - just said that in case :)
And how do I add a file to that POST request using setValue given that I have a file on my hard drive I used to send like Content-Type:image/jpg < ~/Downloads/file.jpg
This shows you how... Look for the body part where they add the image... A Google search for upload image swift post request got me this result :) kaleidosblog.com/…
Lines between let body = NSMutableData() and request.HTTPBody = body
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.