简体   繁体   中英

mysql + json + iphone + webservices

I have created web service in php.

Now I want call that web service in my ios app.

I am using JSON parsing for fetching data .

But it is showing me some error.

My code :

    SBJSON *json = [SBJSON new];
    json.humanReadable = YES;
    responseData = [[NSMutableData data] retain];

    NSString *service = @"/getLastUpdated";
    NSString *str;
    str = @"LastUpdated";


    NSString *requestString = [NSString stringWithFormat:@"{\"LastUpdated\":\"%@\"}",str];

   // [[NSUserDefaults standardUserDefaults] setValue:nil forKey:@"WRONGANSWER"];

    NSLog(@"request string:%@",requestString);
    NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];


    NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"URLName" ofType:@"plist"];
    NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
    NSString *urlLoc = [fileContents objectForKey:@"URL"];
    urlLoc = [urlLoc stringByAppendingString:service];
    NSLog(@"URL : %@",urlLoc);

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: 
                                    [NSURL URLWithString: urlLoc]];  
    NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]];
    [request setHTTPMethod: @"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody: requestData];

    NSError *respError = nil;
    NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];


    if (respError) 
    {
        //        NSString *msg = [NSString stringWithFormat:@"Connection failed! Error - %@ %@",
        //                         [respError localizedDescription],
        //                         [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]]; 
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sing It Say It" 
                                                            message:@"check your network connection" delegate:self cancelButtonTitle:@"OK" 
                                                  otherButtonTitles:nil];
        [alertView show];
        [alertView release];

    } 
    else
    {
        NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];

        NSDictionary *results = [responseString JSONValue];
        NSLog(@"results=%@",results);
        NSString *extractUsers = [results objectForKey:@"d"];

        // NSDictionary *finalResult = [extractUsers JSONValue];
        NSLog(@"Final Result : %@",extractUsers);
        [[NSUserDefaults standardUserDefaults] setValue:@"YES" forKey:@"NAVIGATION"];
        [[NSUserDefaults standardUserDefaults] setValue:extractUsers forKey:@"NEWQUEID"];
    }

Error :

2012-09-24 16:08:47.090 ACTEC_Webservice[3239:f803] -JSONValue failed. Error trace is: (
    "Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x6865bc0 {NSLocalizedDescription=Unrecognised leading character}"
)
2012-09-24 16:08:47.091 ACTEC_Webservice[3239:f803] results=(null)
2012-09-24 16:08:47.092 ACTEC_Webservice[3239:f803] Final Result : (null)

In Response String Log is displaying me this value :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>
<title>404 - File or directory not found.</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;}
fieldset{padding:0 15px 10px 15px;} 
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;} 
h3{font-size:1.2em;margin:10px 0 0 0;color:#000000;} 
#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS", Verdana, sans-serif;color:#FFF;
background-color:#555555;}
#content{margin:0 0 0 2%;position:relative;}
.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
-->
</style>
</head>
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
 <div class="content-container"><fieldset>
  <h2>404 - File or directory not found.</h2>
  <h3>The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.</h3>
 </fieldset></div>
</div>
</body>
</html>

Please help me out.. Thank you.

The line:

NSDictionary *results = [responseString JSONValue];

is throwing an exception because responseString is not json. It is HTML. You need to read the HTML to discover the error:

<h2>404 - File or directory not found.</h2>
<h3>The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable.</h3>

Appears you have the wrong URL.

Too bad, though that JSONValue fails so ungracefully. Given that it does, you will want to provide some protection against that in production code. Either validate the json somehow before attempting to parse, or implement an exception handler.

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