0

I'm using alamofire to upload an image. This is sign up API where you can sign up with your profile photo (this is what I have to upload)

So my code is this (I will replace print(JSON) with another code; this is just for testing what's wrong)

func makeUploadRequest(url: String?) {

    let imageData = NSData(data: UIImageJPEGRepresentation(self.userImage.image!, 1)!)

    Alamofire.upload(.POST, url!, headers: ["Content-Type":"application/json"], multipartFormData: { multipartFormData in
        multipartFormData.appendBodyPart(data: imageData, name: "image_file_1")
        }, encodingCompletion: {
            encodingResult in

            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { (JSON) in
                    print(JSON)
                }

            case .Failure(let encodingError):
                //Show Alert in UI
                print(encodingError)
            }
    })
}

but when I run this code, I come across with this message:

FAILURE: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around
character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}

I know why I get this message, it's because the response is not in JSON format. But the response is actually JSON

{
    result: "success",
    msg: "",
    data: {...}
}

When I test the API with URL, it works just fine.

When I used .responseString instead of .responseJSON: it said something about ASP.NET

.response:

(Optional(<NSMutableURLRequest: 0x7f8353217d50> { URL: url }),
 Optional(<NSHTTPURLResponse: 0x7f8353099040> { URL: url }
{ status code: 500, headers {
"Cache-Control" = private;
"Content-Length" = 5136;
"Content-Type" = "text/html; charset=utf-8";
Date = "Tue, 26 Apr 2016 06:09:03 GMT";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "2.0.50727";
"X-Powered-By" = "ASP.NET";
} }), Optional(<3c68746d ... 2e2d2d3e>), nil)

Any help? Thanks in advance!

Joy
  • 87
  • 1
  • 2
  • 12
  • try `.responseString` instead of `.responseJSON` you will know what error you are making while sending the request. – tush4r Apr 26 '16 at 06:02
  • @Fennec Oh I tried .responseString & .response. I'll edit my question with these – Joy Apr 26 '16 at 06:07

2 Answers2

1

Try to replace Success block :-

case .Success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)
                    AppHelper.hideLoadingSpinner()
                    if response.result.value is NSNull
                    {
                        print("Response nil")
                    }
                    else
                    {
                        if let JSON = response.result.value {
                            var mydict = NSMutableDictionary()
                            mydict = JSON as! NSMutableDictionary

                            if (self.delegate != nil){
                                print("response:--------------------\n %@",mydict)
                            }
                        }
                        else
                        {
                            print("response not converted to JSON")
                        }

                    }
                    upload.response(completionHandler: { (request, response, data, error) -> Void in

                            NSLog("upload.response : data : %@", String(data: data!, encoding: NSUTF8StringEncoding)!)
                            NSLog("upload.response : response : %@", response!)


                        })
    }
Mitul Marsoniya
  • 5,272
  • 4
  • 33
  • 57
  • Tried this; response not converted to JSON! – Joy Apr 26 '16 at 05:54
  • Ok now you want see the response i edit my question just refer that. – Mitul Marsoniya Apr 26 '16 at 05:56
  • upload.response : response : { URL: ~~url~~ } { status code: 500, headers { "Cache-Control" = private; "Content-Length" = 5136; "Content-Type" = "text/html; charset=utf-8"; Date = "Tue, 26 Apr 2016 05:59:39 GMT"; Server = "Microsoft-IIS/7.5"; "X-AspNet-Version" = "2.0.50727"; "X-Powered-By" = "ASP.NET"; } } – Joy Apr 26 '16 at 06:03
  • This is what I've got; HTTP 500 Server error? Hmm. And how come the content-type is "text/html" when I already set it as "application/json"? – Joy Apr 26 '16 at 06:05
  • Now you get what actual problem so you solve with api developer. – Mitul Marsoniya Apr 26 '16 at 06:06
  • My answer solve your crash and help to what actual problem on server side so you get solution. – Mitul Marsoniya Apr 26 '16 at 06:08
  • Some times API working on browser but when we actual run on iPhone then you get this kind of issue . – Mitul Marsoniya Apr 26 '16 at 06:09
  • Ah okay, so this is not about my code? Got it. Thanks a lot! – Joy Apr 26 '16 at 06:13
  • But sorry to ask again, why is "content-type" header is still "text/html"? Is this also because of the server error message? – Joy Apr 26 '16 at 06:17
  • You should send this error to your api developer so he/she change in server side then you get proper response. – Mitul Marsoniya Apr 26 '16 at 06:20
  • Here i get :- http://stackoverflow.com/questions/3418557/how-to-remove-asp-net-mvc-default-http-headers – Mitul Marsoniya Apr 26 '16 at 06:20
0

Check your result if it's a failure or success before getting the value. E.g.:

switch response.result {
case .Success(let value):
    print("Value: \(value)")
    break
case .Failure(let error):
    print("Error: \(error)")
    break
}
Ross
  • 601
  • 7
  • 11