Objective-c to Swift project conversion (Server call)

Asked

Viewed 113 times

2

I have a problem that I will explain, I think I found a way to call the methods that are on the server, however when I call a method that has parameters, I get an error, and when I call a method that has no parameters everything goes well. Can someone explain to me why this is happening or what I’m doing wrong?

Call code of the service

statusCode should be 200, but is 500
resposta do servidor ******** = Optional(<NSHTTPURLResponse: 0x7fc90a626350> { URL: https://*****.*****.com/****.slet request = NSMutableURLRequest(URL: NSURL(string: "https://*****.*****.com/****.svc/rest/ListRules")!)  
        request.HTTPMethod = "POST"

        let postString = "ID=10"    
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
            guard error == nil && data != nil else {                                                          // check for fundamental networking error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("resposta do servidor ******** = \(response)")
            }

            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("responseString ++++++++++++ = \(responseString)")
        }
        task.resume()

The error I get is this::

vc/rest/ListRules} { status code: 500, headers {
    "Cache-Control" = private;
    "Content-Length" = 1937;
    "Content-Type" = "application/xml; charset=utf-8";
    Date = "Wed, 27 Jan 2016 10:39:58 GMT";
    Server = "Microsoft-IIS/8.5";
    "X-AspNet-Version" = "4.0.30319";
    "X-Powered-By" = "ASP.NET";
} })
responseString ++++++++++++ = Optional(<Fault xmlns="http://schemas.microsoft.com/ws/2005/05/envelope/none"><Code>
<Value>Receiver</Value><Subcode><Value xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:InternalServiceFault</Value></Subcode></Code>
<Reason><Text xml:lang="en-US">The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. 
This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.</Text></Reason><Detail>
<ExceptionDetail xmlns="http://schemas.datacontract.org/2004/07/System.ServiceModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><HelpLink i:nil="true"/><InnerException i:nil="true"/>
<Message>The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding.
See the documentation of WebContentTypeMapper for more details.</Message><StackTrace>   at System.ServiceModel.Dispatcher.DemultiplexingDispatchMessageFormatter.DeserializeRequest(Message message, Object[] parameters)&#xD;
   at System.ServiceModel.Dispatcher.UriTemplateDispatchFormatter.DeserializeRequest(Message message, Object[] parameters)&#xD;
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.DeserializeInputs(MessageRpc&amp; rpc)&#xD;
   at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc)&#xD;
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc)&#xD;
   at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc&amp; rpc)&#xD;
   at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</StackTrace><Type>System.InvalidOperationException</Type></ExceptionDetail></Detail></Fault>)

Code that will solve the problem however I am having an error when passing the function parameter

let request = NSMutableURLRequest(URL: NSURL(string: "https://*******.*******.com/******.***/***/METODO")!) request.HTTPMethod = "POST"
var postString:NSString = "ID=23"  //--> ERRO?

request.Httpbody = postString.dataUsingEncoding(Nsutf8stringencoding)

and the error is "Encountered unexpect charater 'I'" and this i is the parameter ID, someone can help me?

  • To get started forget Nsstring. String is the native type of Swift. Change your Guard to guard let data = data where error == nil else { return }

  • Try using ASCII NSASCIIStringEncoding

  • I did what you told me, but it did not work the error persists and is the same. Any more tips? Thanks

  • @Leodabus can’t help me anymore? Thank you

  • There’s no helping you without you knowing what you’re asking

  • Um, I apologize for what I did to misunderstand myself or not understand my doubt. I think I know what the problem is, I don’t know how to solve it. I think the problem lies in the passage of parameters in the method when I’m making the body of the request for service

  • Try to put only the method you don’t know how to pass parameters. Edit your question and try to be clearer and more objective. If the question was clear someone would already have answered to gain the reputation agree?

  • But the method is all the one I have posted. Because he does what he has to do but in the server response comes the error I put. And that’s exactly what I don’t get. The reason for the method I put to success for method calls to the server (which do not need parameters) and error in the method calls to the server (which need parameters). That’s why I can’t get anything out of my initial post. Thank you

  • The problem may be in your url. When you pass a string (query Parameter) you need to add Percent escapes before initializing your url of a look at this answer here and see if this helps you http://stackoverflow.com/a/34834294/2303865

  • @Leo Dabus, after so much struggle I put in my project the Alamofire however in the methods in which they need parameters get Failure in communication. I put on the following link my code may help [(@Gabrielrodrigues, I followed your advice and did with Alamofire however I have a problem methods in which I have to pass parameters get Failure in the request. I place on the Link my code [(http://pasteboard.co/1heVRG8P.png

Show 5 more comments

1 answer

1


I managed to solve my problem and the solution is as follows:

  let URL = NSURL(string: "https://****.*****.com/*****.svc/rest/GetByID")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"

let parameters = ["ID": "23"]

do {
    mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch {
}

mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

Alamofire.request(mutableURLRequest)
    .responseJSON{
        response in
        if let JSON = response.result.value{

            let dataSelected = [JSON.valueForKey("Price")!]         //Quando vem apenas um objecto
            print("RESULTADO \(dataSelected)")
        }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.