Cocoa error 256, When using initWithContentsOfURL: - iphone

i getting data from my site:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", nameTrimmmed, [jsonObject objectForKey:#"email"]];
NSLog(#"%#", website);
NSError *error = nil;
NSString *contents = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:website] encoding:NSUTF8StringEncoding error:&error];
contents have Cocoa error 256. where i wrong?

The issue is in Hebrew characters, you should html-escape them, also try request with English characters instead, to see if it works
- (void)yourMethod
{
NSString *name = #"שימרגוליס";
name = AFURLEncodedStringFromStringWithEncoding(name, NSUTF8StringEncoding);
NSString *website = [NSString stringWithFormat:#"http://www.ba-cafe.com/fbconnect.php?email=%#&name=%#&pass=SwHyK17!",#"email#mail.com",name];
NSLog(#"%#", website);
NSError *error = nil;
NSString *contents = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:website] encoding:NSUTF8StringEncoding error:&error];
}
Where AFURLEncodedStringFromStringWithEncodingis a function from AFNetworking framework

Check the Console log for NSLog(#"%#", website);
You will see something like this:
http://www.mysite.com/fbconnect.php?email=thetrimmedname&name=emailaddress&pass=***
So do this:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", [jsonObject objectForKey:#"email"], nameTrimmmed ];
instead of this:
NSString *website = [NSString stringWithFormat:#"http://www.mysite.com/fbconnect.php?email=%#&name=%#&pass=***", nameTrimmmed, [jsonObject objectForKey:#"email"]];

This is because of the dot in the email address.
Look right here:
Error while trying to access Google translate with NSURL

Related

Read string from a file return nil

I try to read string from a file with :
NSString* path = [[NSBundle mainBundle] pathForResource:#"dirty" ofType:#"txt"];
NSString* content = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&err];
And the string i get is nil. in the error i get :
Error Domain=NSCocoaErrorDomain Code=261 "The operation couldn’t be completed. (Cocoa error 261.)" UserInfo=0x21063410 {NSFilePath=/var/mobile/Applications/78889F89-B83C-480C-A246-999152EE757C/Myapp.app/dirty.txt, NSStringEncoding=4}
Any idea what is the problem?
As mentioned, Cocoa error 261 is NSFileReadInapplicableStringEncodingError which means the encoding of file is different than what you are passing in the API.
For Hebrew language encoding, try this answer
NSString* content = [[NSString alloc] initWithContentsOfFile:path encoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingWindowsHebrew) error:&err];
Hope that helps!
The error seems to be the Encoding Issue ..
If you don't know the encoding of your file, you could try this method:
- (id)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error
Refer HERE
And
Try Something like this:
NSError *error = nil;
NSStringEncoding encoding;
NSString *my_string = [[NSString alloc] initWithContentsOfURL:url
usedEncoding:&encoding
error:&error];
Try this.
NSString* content = [[NSString alloc] initWithContentsOfFile:path encoding:nil error:&err];
or change the type of "encoding" hope it will solve you problem.
Try This
NSString *pathtest = [[NSBundle mainBundle] pathForResource:#"dirty" ofType:#"txt"];
NSString* content = [[NSString alloc] initWithContentsOfFile:pathtest encoding:NSASCIIStringEncoding error:&error];
NSLog(#"Test: %#",content);

Break String that came from Json

I have a String that I got from a webserver which came in json format, but the string is huge with everything in it. I tried using the NSDICTIONARY but to no success. I was wondering what would be the best approach to break this string and add to different strings and eventually put it all in a class of strings. Thanks for the help! Here is my code:
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]init];
[request setURL:[NSURL URLWithString:#"http://mym2webdesign.com/meiplay/paulsuckedabuffalo/artists.php"]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; //Or async request
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError *error=nil;
NSLog(#"HHHHHHHHHHHHHH"); //use this to know how far Im getting
NSLog(returnString); // Look at the console and you can see what the restults are
/*NSDictionary *results = [returnString JSONValue];
NSString *ID = [results objectForKey:#"ID"]; // for example
NSLog(#"ID Number: %#", ID);*/
Here is some of the log i get:
[{"ID":"1","name":"kevin","bio":"kevins bio"},{"ID":"1","name":"kevin","age":"20"},{"ID":"2","name":"Cesar","bio":"Cesar bio"},{"ID":"2","name":"Cesar","age":"19"},{"ID":"3", "name":"Katherine", "bio":"Katherines bio"},{"ID":"3", "name":"Katherine", "age":"22"}]
You are doing it wrong. Its a NSArray of NSDictionaries. So first you need to assign it to NSArray and then loop over it to get each individual NSDictionary. See below.
NSArray *results = [returnString JSONValue];
for(NSDictionary *record in results)
{
NSLog(#"ID: %#", [record objectForKey:#"ID"]);
}
You'll probably be better off just using NSJSONSerialization if your app is targeted for at or over iOS 5.0:
NSArray *JSONArray = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&error];
You might need to experiment with using NSArray vs. NSDictionary, etc., but this should be an overall simpler solution.
Try this :
NSArray *results = [returnString JSONValue];
for (int i=0; i<[results count];i++) {
NSDictionary *DetailDictonary=[results objectAtIndex:i];
NSString *strid=[DetailDictonary objectForKey:#"ID"];
NSString *strName=[DetailDictonary objectForKey:#"name"];
NSString *strBio=[DetailDictonary objectForKey:#"bio"];
// Or You can set it in Your ClassFile
MyClass *classObj=[[MyClass alloc] init];
classObj.strid=[DetailDictonary objectForKey:#"ID"];
classObj.strName=[DetailDictonary objectForKey:#"name"];
classObj.strBio=[DetailDictonary objectForKey:#"bio"];
[YourMainArray addObject:classObj]; //set YourClass to Array
[classObj release];
}

Parsing HTML <Tag> into ios

i am Parsing HTML Tag into iOS using Hpple. i am able to parse the data where the HTML Tag is
<div id="NewsPageSubTitle">
<p><**span** hi how are you>
Using ios code:
NSString *tutorialsXpathQueryString = #"//div[#id='NewsPageArticle']/p/span ";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
but in few case i don't have span, imean the string in html is accessed by tag "p" directly like:
<div id="NewsPageSubTitle">
<p>< hi how are you>
Here I am using ios code as:
NSString *tutorialsXpathQueryString = #"//div[#id='NewsPageArticle']/p ";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
but here i am getting a blank data in response.
can any one let me know how to solve the problem?
Since sometimes the para tag has span and sometimes it does not, I would suggest trying to handle that by looping over the children
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"html"];
NSData * data = [NSData dataWithContentsOfFile:filePath];
TFHpple * tutorialsParser = [[TFHpple alloc] initWithHTMLData:data];
NSString *tutorialsXpathQueryString = #"//div[#id='NewsPageSubTitle']";
NSArray *tutorialsNodes = [tutorialsParser searchWithXPathQuery:tutorialsXpathQueryString];
for (TFHppleElement * element in tutorialsNodes) {
NSLog(#"%#", element);
NSLog(#"%#", [element tagName]);
NSLog(#"%#", [element attributes]);
NSLog(#"%#", [element children]);
for (TFHppleElement *childElement in [element children]) {
NSLog(#"%#", childElement);
}
}
Check with this: https://github.com/mwaterfall/MWFeedParser
This will provide the HTML Parser for iphone sdk.
More help on:
this blog and here.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"image" ofType:#"html" inDirectory:#"New Folder 2"];
NSData * data = [NSData dataWithContentsOfFile:filePath];
NSFileHandle *readHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSString *htmlString = [[NSString alloc] initWithData:[readHandle readDataToEndOfFile] encoding:NSUTF8StringEncoding];
TFHpple * Parser = [[TFHpple alloc] initWithHTMLData:data];
NSString *query = #"//p";
NSArray *nodes = [Parser searchWithXPathQuery:query];
for (TFHppleElement *item in nodes)
{
NSLog(#"Title : %#", item.content);
NSLog(#"URL : %#", [item.attributes valueForKey:#"href"]);
}

how to capture data through web service (php) sql query select with condition from ios iphone sdk

I have the following php file:
<?php
$username="root";
$database="testdb";
mysql_connect(localhost,$username);
$user=$_GET["user"];
$password=$_GET["password"];
$query="SELECT documento FROM person WHERE user='".$user." and password ='".$password."'";
$result=mysql_query($query) or die (mysql_error("error "));
$num=mysql_numrows($result);
mysql_close();
$rows=array();
while($r=mysql_fetch_assoc($result)){
$rows[]=$r;
}
echo json_encode($rows);
?>
to retrieve the information achieved by the following functions but the example did not have the php input conditions and parameters was select * from person here the functions
based in http://www.youtube.com/watch?feature=endscreen&v=IQcLngIDf9k&NR=1
-(void) getData:(NSData *) data{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
}
-(void) start {
NSURL *url = [NSURL URLWithString:kGETUrl];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
now as the sql statement has input parameters is not as code and tried something like this A Simple PHP/MySQL Web Service for iOS but I can not accommodate what I need.
Pass the parameters in the string. Here is an example
-(void) start {
NSString *user = [[NSString alloc] initWithString:#"exampleuser"];
NSString *password = [[NSString alloc] initWithString:#"examplepassword"];
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://myserver.com/myphpfile.php?user=%#?password=%#", user, password];
NSURL *url = [NSURL URLWithString:urlstr];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
As it is password and user it normally is better to use POST instead of GET because then it is not part of the URL which is visible. With POST you can hide it if you have a https line. But I think this is not your main concern right now. The above should work.
I made some change in Hollfeder's code and it worked perfectly :)
-(void) start {
NSString *user = [[NSString alloc] initWithString:#"exampleuser"];
NSString *password = [[NSString alloc] initWithString:#"examplepassword"];
NSString *urlstr = [[NSString alloc] initWithFormat:#"http://myserver.com/myphpfile.php?user=%#&password=%#", user, password];
NSString *urlstr_encoded = [urlstr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSURL *url = [NSURL URLWithString:urlstr_encoded];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}

.Pls file parsing

Iam creating and radio application in which i have to check the authentication and after successful login i get .pls file in which there is actual url which has to be played so
anybody know how to parse .pls file and get the url inside the .pls file.
In my case I have a WWEMAC.pls file in main bundle. In which more than one url exist and I have to extract only those URLs and add them in array in string format. Following code worked for me.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"WWEMAC" ofType:#"pls"];
NSError *errorReading;
NSArray *linesOfText = [[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&errorReading] componentsSeparatedByString:#"\n"];
NSLog(#"Reading error %#",errorReading);
NSString *completeDataInStr = [linesOfText componentsJoinedByString:#" "];
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [detector matchesInString:completeDataInStr options:0 range:NSMakeRange(0, [completeDataInStr length])];
for (NSTextCheckingResult *match in matches)
{
NSString *str = [NSString stringWithFormat:#"%#",match.URL];
NSLog(#"URL str = %#",str);
}
return matches;