简体   繁体   中英

Using NSURLSession with HTTP REST API on IOS in Swift

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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM