how to give componentsSeparatedByString on regular expression in iphone - iphone

Hello friends,
I am doing regulation here i create all and i store in array and print that in console also but i give in group also but when i give componentsSeparatedByString is not working why where i am wrong when i doing this code my application goin crash and log message print this meassage:-
[__NSCFArray componentsSeparatedByString:]: unrecognized selector sent to instance 0x4e283a0
2011-09-12 14:05:48.400 RegexKitLiteDemo[10576:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray componentsSeparatedByString:]: unrecognized selector sent to instance 0x4e283a0
This is my code please some one help me in right direction
-(void)sendRequest
{
// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.bookryanair.com/SkySales/FRSearch.aspx"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
} else {
// inform the user that the download could not be made
}
}
/// this for checking is that Sync is work or not
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
[connection release];
NSString *regexString = #"Stations\\[""(.*)""\\] = new Station\\((.*)new Array\\((.*)\\)\\);";
matchArray = [loginStatus arrayOfCaptureComponentsMatchedByRegex:regexString];
NSLog(#"matchArray: %#", matchArray);
group = [[NSMutableArray alloc] initWithCapacity:[matchArray count]];
for (int i = 0; i < [matchArray count]; i++) {
NSString *temp = [[matchArray objectAtIndex: i] componentsSeparatedByString: #","];
[group addObject: temp];
NSLog(#"group: %#", group);
}
}

The componentsSeparatedByString method is applied on a NSString and it returns and NSArray;
- (NSArray *)componentsSeparatedByString:(NSString *)separator
e.g. NSArray *array = [aString componentsSeparatedByString:#","];
So, in your code, for starters, the following line is wrong;
NSString *temp = [[matchArray objectAtIndex: i] componentsSeparatedByString: #","];

If you are trying to turn an NSArray of NSString objects into a single string separated by a comma, try it this way:
NSString *temp = [[matchArray objectAtIndex:i] componentsJoinedByString:#","];
componentsJoinedByString called on an array will return a single string from the array components.
componentsSeparatedByString called on a string will return an array made up of the string components (depending on the separator)

Also the error u are receiving is encountered when the instance you are calling the method componentsSeparatedByString is invalid. Here since you are already printing MAtcharray using NSLog, i suggest you check if it is properly printed. Also since you are trying to access element by element and call the components.... method on that do check by printing element by element to confirm if it actually exists.

Related

Generating a URL string for NSURLRequest fails to initiate

This one has me pretty confused. If I put in the following:
NSString *LoginURLString = [NSString stringWithFormat:#"http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=13242134"];
//NSLog output: http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=2314084
And use this in a URL request, it works fine, but I need to make this dynamic, so I have it concatenate the URL string with a new UserID by using the following:
NSString *user = [NSString stringWithFormat:#"%#", [[NSUserDefaults standardUserDefaults]stringForKey:#"CustomerID"]];
//user = [[NSUserDefaults standardUserDefaults] stringForKey:#"CustomerID"];
NSString *LoginURLString = [NSString stringWithFormat:#"http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=%#", user];
//NSLog output: http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=2314084
Here is the rest of my request initializer:
NSString *urlString = LoginURLString;
responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
And the other methods that handle the request:
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[responseData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[responseData appendData:data];
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection{
// [connection release];
CommonPickUpArray = [[NSMutableArray alloc] init];
CommonLocationInfoArray = [[NSMutableArray alloc] init];
NSString *data = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
NSLog(#"%#", data);
}
This request never even starts. I really don't understand why. I have tried to output the two strings to the NSLog and either way they look exactly the same. Can anyone explain? Thanks for your help!
Edit: The Connection didFailWithError method is outputting this:
Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0xf6a6f50 {NSUnderlyingError=0xf6a75d0 "bad URL", NSLocalizedDescription=bad URL}
Output from answer 1:
2012-05-08 13:45:24.959 AmericanTaxi[1295:707] Connection failed with error: bad URL
2012-05-08 13:45:24.960 AmericanTaxi[1295:707] for the URL: (null)
Output of urlString and LoginURLString:
2012-05-08 13:57:40.415 AmericanTaxi[1320:707] LoginURLString: http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=2314084
2012-05-08 13:57:40.417 AmericanTaxi[1320:707] urlstring: http://dispatch.americantaxi.com:8080/AT/servlet/OnlineOrderServices?command=retrieveCustomerCommonPlaces&customerId=2314084
In your didFailWithError, check the URL and see why it is bad by adding this to your didFailWithError delegate:
NSLog(#"Connection failed with error: %#", [error localizedDescription]);
NSLog(#"for the URL: %#", [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
Post the result.

NSURLConnection returns data but I cannot read it

This is another simple question who'se answer escapes me after a hour on Google...
A user is typing something into a text field and upon this field loosing focus, I launch an NSURLConnection....
NSString *usernameTry = [sender text];
NSLog(#"username field = %#",usernameTry);
NSString *content = [#"http://www.siebenware.de/Rhythm/user/checkusername.php?username=" stringByAppendingString:usernameTry];
content = [content stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:content] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:5.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
NSLog(#"%#",content);
Then I wait for the response....
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"Received Response");
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
int status = [httpResponse statusCode];
if (!((status >= 200) && (status < 300))) {
NSLog(#"Connection failed with status %#", status);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[resultsData appendData:data];
NSString *resultsString = [[NSString alloc] initWithData:resultsData encoding:NSUTF8StringEncoding];
NSLog(#"received data %# %i",resultsString,[resultsString length]);
if ([resultsString isEqualToString: #"FAIL"]){
NSLog(#"failed to retrieve data");
}else{
resultsObjects = [[resultsString componentsSeparatedByString:#":"] mutableCopy];
if([resultsObjects objectAtIndex:0]==#"usernamecheck"){
if ([resultsObjects objectAtIndex:1]==username.text) {
if ([resultsObjects objectAtIndex:2]==#"NG"){
//set the check marker to bad
[usernameVer setImage:[UIImage imageNamed:#"redcross.png"]];
}else{
//set the check market to good
[usernameVer setImage:[UIImage imageNamed:#"greentick.png"]];
}
}
}
}
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog([NSString stringWithFormat:#"Connection failed: %#", [error description]]);
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Unable to retrieve data" message:[NSString stringWithFormat:#"Error code %i",[error code]] delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
I see the response arrive in didReceiveResponse and am getting 18 bytes of data (which is correct).
However didReceiveData says that the 'data' is null. I know I am missing something exceptionally simple, and I promise to kick myself once this is cleared up.
Regards
Chris H
if you want to change the data into an NSString you can do this:
NSString *responsestring = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", responsestring);
You need work with your data in:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
Because
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
can be called many times
You can do that:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[myData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// TODO: work with data
}
NSMutableData* myData must be instance var.
You need to convert the NSMutableData received by the NSURLConnection delegate method to readable NSString by using the below code
NSString *finalString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
and that should do it.
Try with other encoding..May be ASCII encoding instead of UTF-8..It may work out

parsing json response in my objective-c program

im using SBJSON to parse my response, bus somehow i cant get my data out.
how should i parse this reponed ?
{"StatusCode":0,"Message":"email already exists","Content":{"HasApplication":false,"IsFaceBook":false,"UserActive":false,"UserAuthenticationType":0,"UserCredits":0,"UserDayAdded":0,"UserEmail":null,"UserEmailWasVerified":false,"UserGuid":null,"UserID":0,"UserSellerApproved":false,"UserTokef":0},"TotalCount":0}
i start like this :
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
NSLog(#"%#",response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
NSLog(#"Data recived");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed! Error - %# %#",[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
responseData = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"conenction loading finished");
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString error:nil];
}
but whats next ?i need the StatusCode value and the UserID.
One you have the dictionary, you can use it, for example:
NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString error:nil];
NSNumber * statusCode = [jsonDictionary objectForKey:#"StatusCode"];
NSString * message = [jsonDictionary objectForKey:#"Message"];
NSDictionary * content = [jsonDictionary objectForKey:#"Content"];
// etc...
From the looks of the JSON string, you have a Dictionary with three Key Value pairs, one of those being another Dictionary with several Key Value pairs. So to deal with that once you have assigned the JSON responseString to your NSMutableDictionary:
Should be something like:
NSNumber *statusCode = [jsonDictionary objectForKey:#"StatusCode"];
NSDictionary *contentDict = [jsonDictionary objectForKey#"Content"];
NSString *userID = [contentDict valueForKey#"UserID"];
On a completely different note, if you are going to be doing a lot of web-service interaction, you may want to take a serious look at AFNetworking. It will change your life :)
Also, I can't see why you would need jsonDictionary to be an NSMutableDictionary. Unless you are changing it later on, use NSDictionary, it has less overhead.
well.....
NSMutableDictionary *jsonDictionary = [parser objectWithString:responseString
Maybe it's not NSMutableDictionary, but NSDictionary.
and then:
NSString *statusCode = [jsonDictionary valueForKey:#"StatusCode"];
NSDictionary *contentDict = [jsonDictionary objectForKey#"Content"];
NSString *userID = [contentDict valueForKey#"UserID"];

NSURLConnection shown as leaking in instruments

Hello another stupid question regarding leaks and also NSURLConnection. How do i release it? Is it enough if i release in the following 2 methods?
(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
(void)connectionDidFinishLoading:(NSURLConnection *)connection
Because in instruments it shows me the line where I alloc my connection as the source of leaking.
(EDIT1: OK I don't get it. After the following code my urlConnection has a retain count of 2. WTF?)
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];
This is the line that instruments points me to.
EDIT2: here is some code:
I create the connection here
- (void) makeRequest
{
//NSString *urlEncodedAddress = [self.company.street stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *urlString = [[NSString alloc] initWithFormat:
#"http://maps.google.com/maps/api/geocode/xml?latlng=%f,%f&sensor=false",
bestEffort.coordinate.latitude,bestEffort.coordinate.longitude];
debugLog(#"%#",urlString);
NSURL *url = [[NSURL alloc] initWithString: urlString];
[urlString release];
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL: url];
[url release];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest: urlRequest delegate: self];
debugLog(#"connection created %# rc %i", urlConnection, urlConnection.retainCount);
[urlRequest release];
connection = urlConnection;
}
I release it here
-(void)connection:(NSURLConnection *)_connection didFailWithError:(NSError *)error
{
debugLog(#"ERROR with the connection: %#", error.localizedDescription);
//[activityIndicator setHidden:YES];
debugLog(#"connection will be released or else %# %i", _connection, [_connection retainCount]);
[connection release];
connection = nil;
[webData release];
webData = nil;
if (!cancel)
[delegate rgc_failedWithError: self : error];
isWorking = FALSE;
}
Or here
-(void)connectionDidFinishLoading:(NSURLConnection *)_connection
{
debugLog(#"connection will be released (or else) %# %i", _connection, [_connection retainCount]);
[connection release];
connection = nil;
debugLog(#"DONE. Received Bytes: %d", [webData length]);
//NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
//debugLog(#"%#",theXML);
//[theXML release];
.....
.....
}
EDIT3: Problem solved by not caring whether it's leaking or not! Simple!
You're correct to release it in the delegate methods, however the analysis tools like instruments and the clang analyser aren't clever enough to deal with that and report a false positive. I'd be inclined to file a bug with apple, it will certainly be a duplicate but will tell them that more developers are finding this annoying.

Cannot get HTTP GET request from IPhone application

I am writing a sample PHP Web Service that is sending GET Http request from the iphone to the web server. The server side code is returning JSON Data to iphone, the server side code looks like:
<?php
function getUsers(){
$con=mysql_connect("localhost","root","123456") or die(mysql_error());
if(!mysql_select_db("eventsfast",$con))
{
echo "Unable to connect to DB";
exit;
}
$sql="SELECT * from users";
$result=mysql_query($sql);
if(!$result)
{
die('Could not successfully run query Error:'.mysql_error());
}
$data = array();
while($row = mysql_fetch_assoc($result)){
$data['username'][] = $row['username'];
$data['password'][]= $row['password'];
}
mysql_close($con);
//print_r(json_encode($data));
//return (json_encode($data));
return json_encode('success');
}
getUsers();
?>
Its a simple code that Fetches all the data from the user table and send it to the iphone application.
PHONE APPLICATION
- (void)viewDidLoad {
[super viewDidLoad];
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:8888/GetData.php"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
label.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSArray *luckyNumbers = [json objectWithString:responseString error:&error];
[responseString release];
if (luckyNumbers == nil)
label.text = [NSString stringWithFormat:#"JSON parsing failed: %#", [error localizedDescription]];
else {
NSMutableString *text = [NSMutableString stringWithString:#"Lucky numbers:\n"];
for (int i = 0; i < [luckyNumbers count]; i++)
[text appendFormat:#"%#\n", [luckyNumbers objectAtIndex:i]];
NSLog(text);
label.text = text;
}
}
The Problem
The problem is that nothing is coming on iphone side of the application. The response doesn't contain anything.
#user3171192,
I think there would be problem is you does not passing UserID and Password with NSURLRequest to your web service.Therefore it could may be not give you response of the connection.
Please use
In the portion of
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
NSLog(#"Response of web service %#", responseData);
}
You will get exact response of your code in GDB.
I hope so you it will fixing your problem.
Sorry for English.