iOS API in Parse - One to Many relation - iphone

I am using parse for the backend part of my iPhone App.
We can have a one to many relation in Parse which described in Relational Data.
This code works fine to retrive the data:
PFQuery *query = [PFQuery queryWithClassName:#"Comment"];
PFObject *fetchedComment = [query getObjectWithId:#"0PprArjYi3"];
NSString *content = [fetchedComment objectForKey:#"content"];
printf("%s", [content UTF8String]);
But when I use their codes provided in the Link, it returns null:
PFObject *post = [fetchedComment objectForKey:#"parent"];
[post fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
title = [post objectForKey:#"title"];
}];
printf("%s", [title UTF8String]); // RETURN NULL
Can anybody tell me what is wrong in this code? The problem could be fetchedcomment.
Addenda
This one also got an exception:
PFQuery *query = [PFQuery queryWithClassName:#"Comment"];
PFObject *fetchedComment = [query getObjectWithId:#"0PprArjYi3"];
PFObject *post = [fetchedComment objectForKey:#"parent"];
NSString *title = [post objectForKey:#"title"];
printf("%s", [title UTF8String]);

The method fetchIfNeededInBackgroundWithBlock is, as the name suggests, performed in background. Your code asks for a fetch and then immediately continues to the printf. At that point in time, the data hasn't been fetched yet, so title is probably still nil.
You have two options -
Use a synchronous method, such as [post fetch]: instead of [parent fetchInBackground...].
[post fetch];
title1 = [post objectForKey:#"title"];
Print the title inside the block that gets executed when the fetchInBackground... method finishes.

Related

CHCSVParser - how to load from webserver

I would like to parse csv from webserver which gets updated everyday.I am using the csvparser from this link https://github.com/davedelong/CHCSVParser and I am using this code:
NSError *err = [[[NSError alloc] init] autorelease];
NSString *lunchFileURL = [[NSString stringWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lunchFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:lunchFileURL] encoding:NSUTF8StringEncoding error:&err];
CHCSVParser *p = [[CHCSVParser alloc] initWithContentsOfCSVString:lunchFile usedEncoding:&encoding error:nil];
I get this error :
No visible #interface for 'CHCSVParser' declares the selector 'initWithContentsOfCSVString:usedEncoding:error:'
I checked this link Load remote csv into CHCSVParser and its not working .I am a noob to ios ,Please let me know how to fix this .Really Appreciate the help.Thanks in Advance.
It should probably be:
NSError *err;
NSString *lunchFileURL = [[NSString stringWithFormat:#"http://www.somewhere.com/LunchSpecials.csv"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lunchFile = [NSString stringWithContentsOfURL:[NSURL URLWithString:lunchFileURL]
encoding:NSUTF8StringEncoding
error:&err];
// if you're going to create a CHCSVParser yourself, the syntax is:
CHCSVParser *p = [[CHCSVParser alloc] initWithCSVString:lunchFile
encoding:NSUTF8StringEncoding
error:&err];
// or, if you're going to use NSArray+CHCSVAdditions.h, the syntax might be:
NSArray *array = [[NSArray alloc] initWithContentsOfCSVString:lunchFile
encoding:NSUTF8StringEncoding
error:&err];
Note:
You don't need to alloc/init the NSError object; these classes that take a NSError ** parameter will create the autorelease error object for you if they encounter an error; otherwise they leave it alone;
The CHCSVParser class method is not initWithContentsOfCSVString, but rather initWithCSVString;
Alternatively, if you use the NSArray class extension, then the syntax is arrayWithContentsOfCSVString or initWithContentsOfCSVString; and
You specified an encoding of &encoding, but this parameter is not a pointer, so I don't see how that can possibly be right; I've just specified the encoding.
I assume you want to use the NSArray+CHCSVAdditions category method initWithContentsOfCSVString or arrayWithContentsOfCSVString (which gives you an autorelease object), not the CHCSVParser, but it's up to you.

Solution for a leak in touchXML when no internet and using initWithContentsOfURL

There's a leaking CXMLDocument object shown in instruments everytime, a request to an XML is made to a webservice AND when there's no internet connection available. Here's my code:
NSString *path = ... some URL
NSURL *url = [NSURL URLWithString: path];
CXMLDocument *itemListParser; = [[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil];
... other stuff ...
If we digg deeper and trace initWithContentsOfURL call then we will find this method in "CXMLDocument.m":
- (id)initWithContentsOfURL:(NSURL *)inURL encoding:(NSStringEncoding)encoding options:(NSUInteger)inOptions error:(NSError **)outError
{
if (outError)
*outError = NULL;
NSData *theData = [NSData dataWithContentsOfURL:inURL options:NSUncachedRead error:outError];
if (theData)
{
self = [self initWithData:theData encoding:encoding options:inOptions error:outError];
}
else
{
[self release]; //My suggested fix: We need to release an alloc'ed object because after the "self = null" it will be unable to release it. See the info below.
self = NULL;
}
return(self);
}
It appears, if theData is nil (for example no connection) then self will be nil, and so the result of the call to TouchXML initWithContentsOfURL will be nil too. So, in my code:
CXMLDocument *itemListParser; = [[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil];
I'm alloc'ing a memory but init returns nil, and so itemListParser becomes nil too. So later, trying to release the parser with [itemListParser release] does nothing because release is send to nil.
I was able to fix a leak by adding "[self release]" before "self = NULL" (see the line with my comment in TouchXML initWithContentsOfURL method)

iPhone and MySQL

First I need to say that I am new to iPhone development, so please I need you to be specific!
I'm developing an application for School scientific project,the question is: How can I insert data into a mysql table from UITextFields on the iPhone?
On my application I have 3 UITextFields, so I need to insert those UITextFields values into the mysql table. It doesn't matter the way you know to do that, I'm in a hurry and I just wanna to put it to work.
1-I working with this PHP code
<?php
if (isset ($_GET["matricula"]))
$matricula = $_GET["matricula"];
else
$matricula = "ELO";
$sql="INSERT INTO chatitems (user, message, matricula) VALUES ('$_GET[user]','$_GET[messages]','$_GET[matricula]')";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die(mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
//$sql = "insert into $DB_Table (matricula) values('$matricula');";
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
And I insert this CODE on my application(Xcode 4.1)
2
- (IBAction)insert:(id)sender
{
// create string contains url address for php file, the file name is phpFile.php, it receives parameter :name
NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/phpFile.php?name=%#",txtName.text];
//NSString *strURL = [NSString stringWithFormat:#"http://localhost:8888/phpFile.php?name=%#",txtMatricula.text];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", strResult);
NSString *cont11 = [NSString stringWithFormat:#"http://localhost:8888/UEUO/insertMT.php?name=%#",txtName.text];
NSString *cont21 = [NSString stringWithFormat:#"http://localhost:8888/UEUO/insertMT.php?matricula=%#",txtMatricula.text];
NSData *cont12 = [NSData dataWithContentsOfURL:[NSURL URLWithString:cont11]];
NSData *cont22 = [NSData dataWithContentsOfURL:[NSURL URLWithString:cont21]];
NSString *cont13 = [[[NSString alloc] initWithData:cont12 encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", cont13);
NSString *cont23 = [[[NSString alloc] initWithData:cont22 encoding:NSUTF8StringEncoding]autorelease];
NSLog(#"%#", cont23);
}
This code works fine for only one UItextField, I need three3.
Repenting: How can I insert the values of three UITextFields into a MySql table using PHP and C++?
Please anything is helpful, if you know how please help me or send me a tutorial or a piece of code!
Your PHP script is looking for 3 parameters passed from a single request.
Your iPhone code is sending 2 different requests with 1 parameter each.
Your iPhone code should be sending 1 request with 3 parameters set, as with this sort of request:
NSString *cont11 = [NSString stringWithFormat:#"http://localhost:8888/UEUO/insertMT.php?name=%#&matricula=%#&message=%#",txtName.text, txtMatricula.text, txtMessage.text];
[NSData dataWithContentsOfURL:[NSURL URLWithString:cont11]];
I should also point out that you haven't sanitized your inputs. That's really bad. Sanitize your inputs.

iphone: NSMutableURLRequest returns strange characters for MS Word style apostrophe

We are pulling content off our website using XML/NSMutableURLRequest and sometimes it pulls through the "curly" style apostrophe and quotes, ’ rather than '. NSMutableURLRequest seems to hate these and turns them into the strange \U00e2\U0080\U0099 string.
Is there something that I can to do prevent this? I am using the GET method, so should I be somehow telling it to use UTF-8? Or, am I missing something?
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
NSString *urlStr = [NSString stringWithFormat:#"%#",url];
NSURL *serviceUrl = [NSURL URLWithString:urlStr];
NSMutableURLRequest *serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl];
[serviceRequest setHTTPMethod:#"GET"];
NSURLResponse *serviceResponse;
NSError *serviceError;
app.networkActivityIndicatorVisible = NO;
return [NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:&serviceResponse error:&serviceError];
NSURLConnection returns an NSData response. You can take that NSData response and turn it into a string. Then take this string, turn it back into a NSData object, properly UTF-8 encoding it along the way, and feed it to NSXMLParser.
Example: (Assuming response is the NSData response from your request)
// long variable names for descriptive purposes
NSString* xmlDataAsAString = [[[NSString alloc] initWithData:response] autorelease];
NSData* toFeedToXMLParser = [xmDataAsAString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser* parser = [[[NSXMLParser alloc] initWithData:toFeedToXMLParser] autorelease];
// now utilize parser...
I would suggest replacing those characters using stringByReplacingCharactersInRange:withString: to replace the unwanted strings.
NSString *currentTitle = #"Some string with a bunch of stuff in it.";
//Create a new range for each character.
NSRange rangeOfDash = [currentTitle rangeOfString:#"character to replace"];
NSString *location = (rangeOfDash.location != NSNotFound) ? [currentTitle substringToIndex:rangeOfDash.location] : nil;
if(location){
currentTitle = [[currentTitle stringByReplacingOccurrencesOfString:location withString:#""] mutableCopy];
}
I've done this in the past to handle the same problem you describe.
Try using the stringByReplacingPercentEscapesUsingEncoding:

function to get the file name of an URL

I have some source code to get the file name of an url
for example:
http://www.google.com/a.pdf
I hope to get a.pdf
because the way to join 2 NSStrings I can get is 'appendString' which only for adding a string at right side, so I planned to check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop the checking, return string fdp.a , after that I change fdp.a to a.pdf
source codes are below
-(NSMutableString *) getSubStringAfterH : originalString:(NSString *)s0
{
NSInteger i,l;
l=[s0 length];
NSMutableString *h=[[NSMutableString alloc] init];
NSMutableString *ttt=[[NSMutableString alloc] init ];
for(i=l-1;i>=0;i--) //check each char one by one from the right side of string 'http://www.google.com/a.pdf', when it reach at the char '/', stop
{
ttt=[s0 substringWithRange:NSMakeRange(i, 1)];
if([ttt isEqualToString:#"/"])
{
break;
}
else
{
[h appendString:ttt];
}
}
[ttt release];
NSMutableString *h1=[[[NSMutableString alloc] initWithFormat:#""] autorelease];
for (i=[h length]-1;i>=0;i--)
{
NSMutableString *t1=[[NSMutableString alloc] init ];
t1=[h substringWithRange:NSMakeRange(i, 1)];
[h1 appendString:t1];
[t1 release];
}
[h release];
return h1;
}
h1 can reuturn the coorect string a.pdf, but if it returns to the codes where it was called, after a while system reports
'double free
*** set a breakpoint in malloc_error_break to debug'
I checked a long time and foudn that if I removed the code
ttt=[s0 substringWithRange:NSMakeRange(i, 1)];
everything will be Ok (of course getSubStringAfterH can not returns the corrent result I expected.), no error reported.
I try to fix the bug a few hours, but still no clue.
Welcome any comment
Thanks
interdev
The following line does the job if url is a NSString:
NSString *filename = [url lastPathComponent];
If url is a NSURL, then the following does the job:
NSString *filename = [[url path] lastPathComponent];
Try this:
Edit: from blow comment
NSString *url = #"http://www.google.com/a.pdf";
NSArray *parts = [url componentsSeparatedByString:#"/"];
NSString *filename = [parts lastObject];
I think if you have already had the NSURL object, there is lastPathComponent method available from the iOS 4 onwards.
NSURL *url = [NSURL URLWithString:#"http://www.google.com/a.pdf"];
NSString *filename = [url lastPathComponent];
Swift 3
Let's say that your url is http://www.google.com/a.pdf
let filename = url.lastPathComponent
\\filename = "a.pdf"
This is more error free and meant for getting the localized name in the URL.
NSString *localizedName = nil;
[url getResourceValue:&localizedName forKey:NSURLLocalizedNameKey error:NULL];
I haven't tried this yet, but it seems like you might be trying to do this the hard way. The iPhone libraries have the NSURL class, and I imagine that you could simply do:
NSString *url = [NSURL URLWithString:#"http://www.google.com/a.pdf"];
NSString *path = [url path];
Definitely look for a built in function. The libraries have far more testing and will handle the edge cases better than anything you or I will write in an hour or two (generally speaking).