NSXMLParser with encoded Data in String - ios

I want to program a NSXMLParser and I have the data for this lying in a NSString (encoded).
If I put the NSString to NSLog it gives me the right lines I need. But when I want to start the Parser with the data from that NSString it doesn't start.
Here is my code:
The interface:
#interface StundenplanParser () <NSXMLParserDelegate>
#end
The method that gets called from the ViewController:
-(void)parserStart
{
// Create your request string with parameter name as defined in PHP file
NSString *myRequestString = [NSString stringWithFormat:#"matr=%#&pressme=%#",#"33886",#"S T A R T"];
// Create Data from request
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: #"http://www2.htw-dresden.de/~rawa/cgi-bin/auf/raiplan_app.php"]];
// set Request Type
[request setHTTPMethod: #"POST"];
// Set content-type
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
// Set Request Body
[request setHTTPBody: myRequestData];
// Now send a request and get Response
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSASCIIStringEncoding];
NSLog(#"Response:%#\n",[response substringToIndex:64]);
// If I would use NSASCIIStringEncoding in the following line, the data would be nil
NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
if (!parser) NSLog(#"Error with parser");
else NSLog(#"parser successfully initialised");
[parser setDelegate:self];
[parser parse];
}
NOTE: In my response (NSString*) is the code that I want to parse. If I print it out using NSLog I see the source code of the website..
Now I want to show only the elements the NSXMLParser found with this:
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
NSLog(#"found element: %#", elementName);
}
I hope it's not a problem that I left the url in the code. I just want to parse the schedule from my university.
I hope you understand what I mean and you could help me.
EDIT: My Problem is not that I don't get the XML. My Problem is that the parser won't start.. I edited the code.
EDIT2: The output from the response is:
2013-11-18 23:52:16.008 University[17210:70b] Response:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN
So it seems like it worked, but the problem is the encoding of this into a NSData instance that I need to initialize my parser.
EDIT3:
After implementing the parser:parseErrorOccurred I got the following error in the Console:
2013-11-19 08:58:26.190 University[17458:70b] ERROR while parsing: The operation couldn’t be completed. (NSXMLParserErrorDomain error 65.)

Translating with Google, the website
http://www2.htw-dresden.de/~rawa/cgi-bin/auf/raiplan_app.php
says 'Create a schedule in csv format' and entering the matriculation number from your code 33886, it returns a web page that has in its the data you're trying to get at:
<Stunde>
<titel>Englisch C1 III/SI (w.o.)</titel>
<kuerzel>Engl_C1 Üw3/SI Technik</kuerzel>
<raum>S 334</raum>
<dozent>Kilian</dozent>
<datum>16.10.2013</datum>
<anfang>7:30</anfang>
<ende>9:00</ende>
</Stunde>
If you extract this data and form a new XML string, then the XML Parser will run. The tag is where this data begins, and the last one is followed by a , so this code will extract out the elements:
NSRange startRange = [dataString rangeOfString:#"<Stunde>"];
NSString *dataAfterHtml = [dataString substringFromIndex:startRange.location];
NSRange endRange = [dataAfterHtml rangeOfString:#"<br>"];
dataAfterHtml = [dataAfterHtml substringToIndex:endRange.location];
NSString *formattedXML = [NSString
stringWithFormat:#"<data>%#</data>",
dataAfterHtml];
now give this the parser
NSData *data = [formattedXML dataUsingEncoding:NSUTF8StringEncoding];
xmlParser = [[NSXMLParser alloc] initWithData:data];

You are interpreting the data as ASCII and then encoding it as UTF8, you are going to end up with an invalid string or with a string with invalid characters. Try this:
...
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:returnData];
[parser setDelegate:self];
[parser parse];

You problem is that you are not URLEncoding the data, but feeding it draw into the HTTP body. In this:
NSMutableData *body = [NSMutableData data];
NSString *postWerte = #"matr=XXXXX&lang=1&aktkw=1&pressme=S T A R T";
[body appendData:[postWerte dataUsingEncoding:NSUTF8StringEncoding]];
you need to URLEncode "S T A R T", and should bee really URLencoding every string that follows an equal sign. (UPDATE: so it works as is - my service is way picker and I must encode. YMMV!)
EDIT:
So try changing your code a bit, and if it still fails then please post the first line or two of the returned data:
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
assert(returnData); // you should be suppling an error pointer just in case but this will do for now
// Log Response
{
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSASCIIStringEncoding];
NSLog(#"%#",[response substringToIndex:64]); // or a bit mor
}
NSXMLParser *parser = [[NSXMLParser alloc] initWithData: returnData];
assert(parser); // will be nil if anything has gone wrong, obviously in your real code put an if test
[parser setDelegate:self]; // no affect for nil object
[parser parse];// no affect for nil object
EDIT2:
BTW, I missed this, and it may not make a difference, but the parser object has no property "delegate", you technically should be using the setter:
[parser setDelegate:self];
Also, you did implement the following, right?
parserDidStartDocument: // which I assume you never see, right
parser:validationErrorOccurred:
parser:parseErrorOccurred:
parserDidEndDocument: // you never see this either?
If parser is nil, dump the whole returned data as a UTF8 string (per the log code). Also, try looking for an error:
dispatch_async(dispatch_get_main_queue(), ^
{
NSLog(#"PARSE ERROR: %#", [parser parseError]);
} );

Related

JSON parse error in iOS

I am trying to parse json response(which I get from result tag of a SOAP webservice response) as shown in pictures with following lines.
NSString *soapMessage = [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
"<GetPhotoSession xmlns=\"http://tempuri.org/\">"
"<UserID>%#</UserID>"
"<photoSessionID>%#</photoSessionID>"
"</GetPhotoSession>"
"</soap:Body>"
"</soap:Envelope>",[HelperClass retrieveStringForKey:kUserID],self.currentSession.sessionID];
NSURL *url = [NSURL URLWithString:kBaseURL];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:#"%lu", (unsigned long)[soapMessage length]];
[theRequest addValue: #"text/xml; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[theRequest addValue: #"http://tempuri.org/GetPhotoSession" forHTTPHeaderField:#"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection ) {
self.webResponseData = [NSMutableData data];
}else {
NSLog(#"Some error occurred in Connection");
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[self.webResponseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.webResponseData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"Some error in your Connection. Please try again.");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"Received Bytes from server: %d", [self.webResponseData length]);
NSString *myXMLResponse = [[NSString alloc] initWithBytes: [self.webResponseData bytes] length:[self.webResponseData length] encoding:NSUTF8StringEncoding];
NSLog(#"%#",myXMLResponse);
NSError *errorPointer;
NSDictionary *dict = [XMLReader dictionaryForXMLString:myXMLResponse error:&errorPointer];
NSString *jsonData = dict[#"soap:Envelope"][#"soap:Body"][#"GetPhotoSessionResponse"][#"GetPhotoSessionResult"][#"text"];
NSData *data = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&errorPointer];
NSLog(#"%#",[json objectForKey:#"Head"]);
}
But I am getting nil in "json" object. Here is the pastie link for JSON response http://pastie.org/9799331. Following is the description of error pointer.
Printing description of errorPointer:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0x7d0156a0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
Is this your own web service or an existing one? If this is your own, are you sure your JSON is actually correct?
I believe the problem is here:
"ImageBase64Data": "/9j/4AAQSkZJRgABAQA .... blah blah ==
"
Note the key point here. That the closing double quote is on the next line. It should be
"ImageBase64Data": "/9j/4AAQSkZJRgABAQA .... blah blah =="
For future reference, it is far easier if you cut and paste the JSON payload text in your question versus showing an image.
So grabbing your data from here:
http://pastie.org/9799331#2,22,482
I have run it through this code:
NSError *error = nil;
NSString *path = [[NSBundle mainBundle] pathForResource:#"badjson" ofType:#"txt"];
NSString *jsonStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
// jsonStr = [[jsonStr componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:#""];
NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"Error is %#", error);
NSLog(#"JSON is %#", json);
Note that I have one commented out line right now. When I do this, it fails. However the failure is different than what you listed above. I get.
Error is Error Domain=NSCocoaErrorDomain Code=3840 "The operation
couldn’t be completed. (Cocoa error 3840.)" (Unescaped control
character around character 120.) UserInfo=0x7f9519f71510
{NSDebugDescription=Unescaped control character around character 120.}
If I uncomment out that line, then it works. Only showing a snippet of the output:
2014-12-26 12:03:35.020 Sample[49732:6379864] Error is (null)
2014-12-26 12:03:35.022 Sample[49732:6379864] JSON is {
Head = (
{
ID = 1092;
ImageBase64Data = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDACAWGBwYFCAcGhwkIiAmMFA0MCwsMGJGSjpQdGZ6eHJmcG6AkLicgIiuim5woNqirr7EztDOfJri8uDI8LjKzsb/
Your data is using an base64 output which uses newlines to delimit each encoded line. This is why you see at the end the text that looks like:
==
","ImageName"
You'll also notice the vast majority of lines in the Base64 look uniform .. because of this delimiting.
Strip out the newlines using this (you need to modify it for you code)
jsonStr = [[jsonStr componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:#""];
If that doesn't work, then you need to provide some more info:
-Is the output taken from Xcode console?
-Add in your code where the NSLog exists to get the output (if you don't have it, then please add one).
-Once you add the NSLog, provide that output
While it may seem like you've "already provided that info", there is obviously a gap in information. Else I would expect to see the same NSError output. So we're either missing steps, or maybe there is some other variance. For example, I'm running this in an iOS 8 simulator. Not that it should matter too much, but there is always a possibility that you're running on an older version of iOS that parses the JSON differently.

Error Domain=NSURLErrorDomain Code=-1000 "bad URL"

Following problem:
I get every time the error -1000, but really don't know what I can change. I've tried it with GET and another sending method. But I get every time the same error.
Does someone see my mistake?
thanks
NSString *get =[[NSString alloc] initWithFormat:#"mobileNumber=%#&deviceToken=%#",myMobileNumber,myDeviceToken];
[get stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://myHomepage.net/login.php?%#",get]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseData = #"";
if ([response statusCode] ==200 )
{
responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"---------responseData: %#",responseData);
return responseData;
} else {
You're not saving the result of stringByAddingPercentEscapesUsingEncoding. So, instead of:
[get stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
You need:
get = [get stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
FYI, while the above fix will now successfully percent escape all characters not permitted within in a URL, there are actually some characters that are acceptable in a URL, but are not acceptable within a parameter value (e.g. a + which is interpreted as a space, or & which delineates parameters).
It is important to percent escape the values used in the parameters of the request in such a way that you escape not only those characters that are not legal in a URL, but also a few that are otherwise legal in a URL, but are not permitted within a parameter value.
Unfortunately the standard stringByAddingPercentEscapesUsingEncoding method does not do this. But the CFURL function CFURLCreateStringByAddingPercentEscapes does. You apply this function to the individual parameter values. Here is a method that performs the necessary toll-free bridging between this function and ARC:
- (NSString *)percentEscapeString:(NSString *)string
{
NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef)string,
(CFStringRef)#" ",
(CFStringRef)#":/?#!$&'()*+,;=",
kCFStringEncodingUTF8));
return [result stringByReplacingOccurrencesOfString:#" " withString:#"+"];
}
You can use this method as follows:
NSString *get =[[NSString alloc] initWithFormat:#"mobileNumber=%#&deviceToken=%#", [self percentEscapeString:myMobileNumber], [self percentEscapeString:myDeviceToken]];
NSURL *url=[NSURL URLWithString:[NSString stringWithFormat:#"http://myHomepage.net/login.php?%#",get]];
This should correctly percent escape the parameter values of the string, regardless of the presence of these reserved characters, or not.

NSHTTPURLResponse release message sent to deallocated instance

I have the following code to get data from server;
-(void)loginForFaceBook
{
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:#"https://www.googleapis.com/auth/plus.me"
clientID:#"27615...6qdi60qjmachs.apps.googleusercontent.com"
clientSecret:#"Fs8A...u2PH"
keychainItemName:#"OAuth2 Sample:
Google+"
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)];
[[self navigationController] pushViewController:viewController
animated:YES];
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (error != nil) {
// Authentication failed (perhaps the user denied access, or closed the
// window before granting access)
NSLog(#"Authentication error: %#", error);
NSData *responseData = [[error userInfo] objectForKey:#"data"]; //
kGTMHTTPFetcherStatusDataKey
if ([responseData length] > 0) {
// show the body of the server's authentication failure response
// NSString *str = [[NSString alloc] initWithData:responseData
// encoding:NSUTF8StringEncoding];
// NSLog(#"%#", str);
}
// self.auth = nil;
} else {
// NSString *authCode = [NSString alloc]in;
NSMutableURLRequest * request;
request = [[NSMutableURLRequest alloc] initWithURL:[NSURL
URLWithString:#"http://api.kliqmobile.com/v1/tokens"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] ;
NSLog(#"%#",auth);
NSLog(#"ho gya success %# :::: %# :::: %#", auth.accessToken,
auth.refreshToken, auth.code);
NSMutableURLRequest * response;
NSError * error;
request.URL = [NSURL URLWithString:#"http://api.kliqmobile.com/v1/tokens"];
NSString *post = [NSString stringWithFormat:#"
{\"token\":\"%#\",\"secret\":\"%#\",\"service\":\"%#\",\"handle\":\"%#\"}",
auth.accessToken,auth.code,#"google",nil];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
error = nil;
response = nil;
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request
delegate:self];
[connection start];
}
I have implemented the NSURLConnection delegtes method and data is printing well like this
- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
NSMutableURLRequest * response;
NSError * error;
NSLog(#"Did Receive Data %#", [[NSString alloc]initWithData:data
encoding:NSUTF8StringEncoding]);
NSMutableURLRequest * requestContacts;
requestContacts = [[NSMutableURLRequest alloc] initWithURL:[NSURL
URLWithString:#"http://api.kliqmobile.com/v1/contacts"]
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60] ;
[requestContacts setHTTPMethod:#"GET"];
[requestContacts setAllHTTPHeaderFields:headers];
error = nil;
response = nil;
NSData* data1 = [NSURLConnection sendSynchronousRequest:requestContacts
returningResponse:&response error:&error];
NSLog(#"WE GET THE REQUIRED TOKAN DATA %# :: %# :: %#", [[NSString alloc]
initWithData:data1 encoding: NSASCIIStringEncoding], error ,response);
}
but after that my app get crashed and it is giving following error;
[NSHTTPURLResponse release]: message sent to deallocated instance 0xcb51070.
please suggest me how to do this.
A couple of thoughts:
What is the intent of your didReceiveData method? There are a bunch of issues here:
You really shouldn't be doing a synchronous network request in the middle of a NSURLConnectionDataDelegate method.
You shouldn't be doing synchronous requests at all, but rather do them asynchronously.
What is the connection between receiving data and your creation of this new request? You're not using the data in the request, so why do it here?
The typical pattern is:
The didReceiveResponse should instantiate a NSMutableData object in some class property.
The only function of didReceiveData should be to append the received data to the NSMutableData. Note, this method may be called multiple times before all the data is received.
In connectionDidFinishLoading, you should initiate any next steps that you take upon successful completion of the request. If you wanted to do start another asynchronous network request when the initial request is done, do that here.
In didFailWithError, you obviously handle any failure of the connection.
When you call connectionWithRequest, you should not use the start method. Only use start when you use initWithRequest:delegate:startImmediately: with NO for the startImmediately parameter. Otherwise the connection starts automatically for you and you're only starting it a second time.
Unrelated to your original question, but your creation of post string cannot be right. You're missing a parameter value. Even better, rather than creating JSON manually, use NSDictionary and then use NSJSONSerialization to make the NSData object containing the JSON from this dictionary. That's much safer:
NSDictionary *params = #{#"token" : auth.accessToken,
#"secret" : auth.code,
#"service" : #"google",
#"handle" : #""};
NSError *error;
NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
Clearly, supply whatever you need for the handle value.
A tangential process-related observation, but I'm wondering if you're taking advantage of everything Xcode offers. For example, your declaration of response as a NSMutableURLRequest but then using that as a parameter to sendSynchronousRequest should have generated a compiler warning. The same thing is true with your stringWithFormat for your post string (my third point). That should have generated a warning, too.
Neither of these are immediately relevant, but I wonder if you are failing to heed any other compile-time warnings. These warnings are your best friend when writing robust code and I would recommend resolving all of them. To go a step further, you should also run the project through the static analyzer ("Analyze" on "Product" menu, or shift+command+B), and resolve anything it points out, too.

Outputting a string from NSXMLParser

I'm new to Objective C and I am using a helper that returns an XML payload from a web service as an NSXMLParser. I need to get that payload as either an NSString of XML or as an NSData object so that I can use it in another library that converts the payload to an NSDictionary.
Is there an easy way to convert this XML to a string? From the docs, I see that I could write my own string builder using the events of NSXMLParser but this feels like re-inventing the wheel compared to working with XML in other languages.
Will this work for you?
NSString *googleString = #"http://www.google.com";
NSURL *googleURL = [NSURL URLWithString:googleString];
NSError *error;
NSString *googlePage = [NSString stringWithContentsOfURL:googleURL
encoding:NSASCIIStringEncoding
error:&error];
from here
Reading HTML content from a UIWebView
From here you should be able to covert to NSXmlParser or NSData but if you make this request to the service it should return the xml as string.
You can convert the NSMutableData to a string:
You send the request:
conexion = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (conexion) {
webData = [NSMutableData data];
}
Then you parse the webData to string. In this function: connectionDidFinishLoading
NSString *XML = [[NSString alloc]
initWithBytes: [webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
If you need to display the result
NSLog(#"%#", XML);

Web service method not hit when called via Objective C

My App_Code/IGetEmployees.vb file
<ServiceContract()> _
Public Interface IGetEmployees
<OperationContract()> _
<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped, UriTemplate:="json/contactoptions")> _
Function GetAllContactsMethod(strCustomerID As String) As List(Of NContactNames)
End Interface
My App_Code/GetEmployees.vb file
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function GetAllContactsMethod(strCustomerID As String) As List(Of NContactNames) Implements IGetEmployees.GetAllContactsMethod
Utilities.log("Hit get all contacts at 56")
Dim intCustomerID As Integer = Convert.ToInt32(strCustomerID)
Dim lstContactNames As New List(Of NContactNames)
'I add some contacts to the list.
Utilities.log("returning the lst count of " & lstContactNames.Count)
Return lstContactNames
End Function
NContactNames is a class with 3 properties.
So i am using ASP.NET web services to retrieve information from SQL server and pass it to my iPad in JSON format. I have a problem with parameter passing. So like you see i have 2 files IGetEmployees.vb and GetEmployees.vb. I am implementing the method GetAllContactsMethod. What's happening is the two lines in GetEmployees.vb file (Utilities.log), they never get logged. The function is not getting called at all.
My objective c code to call this function
NSString *param = [NSString stringWithFormat:#"strCustomerID=%#",strCustomerID];
jUrlString = [NSString stringWithFormat:#"%#",#"http://xyz-dev.com/GetEmployees.svc/json/contactoptions"];
jurl = [NSURL URLWithString:jUrlString];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:jurl];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(#" request string is %#",[[request URL] absoluteString]);
NSLog(#"Done");
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if(theConnection)
{
jData = [NSMutableData data];
NSError *jError;
NSMutableDictionary *json =[NSJSONSerialization JSONObjectWithData:jData options:kNilOptions error:&jError];
NSLog(#"%#",json); //Gets Here and prints (null)
NSLog(#"Done"); //prints this as well.
}
else
{
NSLog(#"No");
}
At the time of posting this code the "if" statement is true and (null) is printed followed by "Done"
The output of my absolute request is:
request string is http://xyz-dev.com/GetEmployees.svc/json/contactoptions
This is the first time i am writing json to accept parameters. So i might be missing something.What is it?Why is the function not getting called at all on the Visual Studio side. If you need more info please ask.Thanks...
this is the moethod in Objetive-C, for that.
-(void) insertEmployeeMethod
{
if(firstname.text.length && lastname.text.length && salary.text.length)
{
NSString *str = [BaseWcfUrl stringByAppendingFormat:#"InsertEmployee/%#/%#/%#",firstname.text,lastname.text,salary.text];
NSURL *WcfSeviceURL = [NSURL URLWithString:str];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:WcfSeviceURL];
[request setHTTPMethod:#"POST"];
// connect to the web
NSData *respData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// NSString *respStr = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:respData
options:NSJSONReadingMutableContainers
error:&error];
NSNumber *isSuccessNumber = (NSNumber*)[json objectForKey:#"InsertEmployeeMethodResult"];
//create some label field to display status
status.text = (isSuccessNumber && [isSuccessNumber boolValue] == YES) ? [NSString stringWithFormat:#"Inserted %#, %#",firstname.text,lastname.text]:[NSString stringWithFormat:#"Failed to insert %#, %#",firstname.text,lastname.text];
}
}
Before to run the code, test your URL with POSTMAN, is an app from Google Chrome.
regards.

Resources