Domanda

Since RubyMotion appears to do a lot of type-conversion at compile-time, I'm having trouble passing in a proper dataType into a NSMutableURLRequest POST request. It's expecting NSData, but I can't figure out how to type an NSString variable to NSData without throwing an error. Without typecasting, our SOAP server can't properly receive the data and I get the dreaded (and vague) "The data at the root level is invalid. Line 1, position 1" error.

This is the problematic line:

postXML = "<xml><whatever>hey</whatever></xml>"
postData = ( postXML as NSData ).dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: true );

request = NSMutableURLRequest.alloc.init
request.setURL( NSURL.URLWithString( "https://services.sbx1.cdops.net/v4.3/SubscriberServicePox.svc/Login" ) )
request.setHTTPMethod( "POST" )

request.setValue( "application/xml", forHTTPHeaderField: "Content-Type" )
request.setHTTPBody( postData, dataUsingEncoding:NSUTF8StringEncoding )

theConnection = NSURLConnection.alloc.initWithRequest( request, delegate:self )

Any help would be appreciated.

È stato utile?

Soluzione

Your understanding of what is going on has some holes, so let's break it down.

postXML = "<xml><whatever>hey</whatever></xml>"
postData = ( postXML as NSData ).dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: true );

I'm not sure where you got ( postXML as NSData ) from but it is not valid and makes no sense. dataUsingEncoding:allowLossyConversion: is an Objective-C method declared on NSString not NSData. The correct way to call it would be like this

postData = postXML.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

Ruby motion doesn't do type conversions for you, Ruby does not and Objective-C does not. If you send a message to a instance of a class that does not respond to the message you send it, you will crash/raise an exception.

When you call

postXML.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

you are not doing type casting, you are sending the message dataUsingEncoding:allowLossyConversion: to an instance of NSString. This will cause a new completely new object (an instance of NSData) to be returned.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top