Xcode Parse Json Data - iphone

My code below was working, before, but suddenly it stopped working. Could anyone tell me what I'm doing wrong?
Output of NSLog():
2013-05-14 16:06:35.475 Run.PH[1502:19a03] background = (null)
2013-05-14 16:06:35.476 Run.PH[1502:19a03] logo = (null)
2013-05-14 16:06:35.476 Run.PH[1502:19a03] json = (null)
2013-05-14 16:06:35.476 Run.PH[1502:19a03] welcome = (null)
Codes:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *urlString = [NSString stringWithFormat:#"http://run.ph/json/test_json_dyna.jsp"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
if(data != nil)
{
NSError *error;
_json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
_welcomeMessage.text = [[_json objectForKey:#"welcome"] objectForKey:#"message"];
NSString *background = [[_json objectForKey:#"welcome"] objectForKey:#"background"];
NSString *logo = [[_json objectForKey:#"welcome"] objectForKey:#"logo"];
NSLog(#"background = %#", background);
NSLog(#"logo = %#", logo);
NSLog(#"json = %#", _json);
NSLog(#"welcome = %#", _welcomeMessage.text);
NSURL *urlBackground = [NSURL URLWithString:background];
NSData *dataBackground = [NSData dataWithContentsOfURL:urlBackground];
[_background setImage:[UIImage imageWithData:dataBackground]];
NSURL *urlLogo = [NSURL URLWithString:logo];
NSData *dataLogo = [NSData dataWithContentsOfURL:urlLogo];
[_logo setImage:[UIImage imageWithData:dataLogo]];
}
else
{
NSLog(#"Error!");
}
[self.view reloadInputViews];
}

Just NSLog your URL response you will get wats wrong with your json.
Try this
NSString *respo = [NSString stringWithContentsOfURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSLog(#"Response - %#",respo);
It has return "\r" and newline character "\n" with your response.
Check this
EDIT
Now your URL is working fine, problem was with your web service end.

Related

UITextField and NSURL URLWithString

I have built a translate application in ios. The application uses the Yandex translation api. I followed this tutorial: http://www.raywenderlich.com/5492/working-with-json-in-ios-5
My ViewController.m looks like this (I took out my api key):
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#import "ViewController.h"
#end
#interface NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress;
-(NSData*)toJSON;
#end
#implementation NSDictionary(JSONCategories)
+(NSDictionary*)dictionaryWithContentsOfJSONURLString:(NSString*)urlAddress
{
NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString: urlAddress] ];
__autoreleasing NSError* error = nil;
id result = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
-(NSData*)toJSON
{
NSError* error = nil;
id result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];
if (error != nil) return nil;
return result;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
// NSData* data = [[NSData dataWithContentsOfURL: TranslateText] ];
NSData*data = [NSURL URLWithString: [NSString stringWithFormat: #"https://translate.yandex.net/api/v1.5/tr.json/translate?key=apikeys&lang=en-es&text=%#", textfield.text]];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* TranslatedText = [json objectForKey:#"text"]; //2
NSLog(#"Text that was translated: %#", TranslatedText); //3
// 1) Get the latest loan
//NSDictionary* ttext = [TranslatedText objectAtIndex:0];
NSString* ttext = [TranslatedText objectAtIndex:0];
// 3) Set the label appropriately
humanReadble.text = [NSString stringWithFormat:#"%#",
//[ttext objectForKey:#"name"],
ttext];
}
#end`
When I run the app, I get the error Thread 1: signal SIGABRT on this line of code:
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
What should I do?
The error in your code is the use of the colon there. You should have the line be...
[NSURL URLWithString: [NSString stringWithFormat: #"https://translate.yandex.net/api/v1.5/tr.json/translate?apikeyes&text=%#", textfield.text];
Also, I do not know why you would do a #define. Grab the information in the method for handling the button getting pressed.
NSURL * translateURL = [NSURL URLWithString: [NSString stringWithFormat: #"https://translate.yandex.net/api/v1.5/tr.json/translate?apikeyes&text=%#", textfield.text];

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];
}

Weird NSString vs NSURL behavior

I have a class which parse an XML feed. In that class I have to following method:
-(id)loadXMLByURL:(NSString *)urlString name:(NSString*)name{
NSString *urls = [[NSString alloc]initWithFormat:#"%#%#" , urlString, name];
NSLog(#"STRING URL: %#" , urls);
NSURL *url = [NSURL URLWithString:urls];
NSLog(#"%#" , url);
parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
parser.delegate = self;
BOOL success = [parser parse];
if (success) {
NSLog(#"No error");
}else{
NSLog(#"Error: %#" , parser.parserError);
}
return self;
}
The first NSLog is the correct url, however the NSURL comes out as (null)
Here's where I call the method:
//f is an object where I store the value of name from another feed, which I have to use as a parameter in the url for this feed
NSString *name = f.name;
myParser = [[MyParser alloc]loadXMLByURL:#"http://myurl.com/names.asp?name=" name:name];
If I NSLog name here, it shows the right value.
Anyone have any idea why the NSURL comes out as (null)?
You'll want to escape name.
Add a category on NSString and then call [name urlEncodedString]. e.g.:
#implementation NSString (URLEncoding)
- (NSString *)urlEncodedString
{
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
kCFStringEncodingUTF8);
}
#end
Use the following..
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat::#"%#%#" , urlString, name]]];
parser = [[NSXMLParser alloc] initWithData: data];
parser.delegate = self;
BOOL success = [parser parse];
if (success) {
NSLog(#"No error");
}else{
NSLog(#"Error: %#" , parser.parserError);
}
return self;

error in uploading photo on facebook wall using graph API

I am going to work on iphone app which upload the photos on facebook wall.
I am using this code
here
- (void)rateTapped:(id)sender {
NSString *likeString;
NSString *filePath = nil;
if (_imageView.image == [UIImage imageNamed:#"angelina.jpg"]) {
filePath = [[NSBundle mainBundle] pathForResource:#"angelina" ofType:#"jpg"];
likeString = #"babe";
} else if (_imageView.image == [UIImage imageNamed:#"depp.jpg"]) {
filePath = [[NSBundle mainBundle] pathForResource:#"depp" ofType:#"jpg"];
likeString = #"dude";
} else if (_imageView.image == [UIImage imageNamed:#"maltese.jpg"]) {
filePath = [[NSBundle mainBundle] pathForResource:#"maltese" ofType:#"jpg"];
likeString = #"puppy";
}
if (filePath == nil) return;
NSString *adjectiveString;
if (_segControl.selectedSegmentIndex == 0) {
adjectiveString = #"cute";
} else {
adjectiveString = #"ugly";
}
NSString *message = [NSString stringWithFormat:#"I think this is a %# %#!", adjectiveString, likeString];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/photos"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addFile:filePath forKey:#"file"];
//[request setFile:filePath withFileName:#"myphoto.jpg" andContentType:#"image/jpeg" forKey:#"photo"];
[request setPostValue:message forKey:#"message"];
[request setPostValue:_accessToken forKey:#"access_token"];
[request setDidFinishSelector:#selector(sendToPhotosFinished:)];
[request setDelegate:self];
[request startAsynchronous];
}
here i got Photo id is: (null)
- (void)sendToPhotosFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *photoId = [responseJSON objectForKey:#"id"];
NSLog(#"Photo id is: %#", photoId);
NSString *urlString = [NSString stringWithFormat:#"https://graph.facebook.com/%#?access_token=%#", photoId, [_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *newRequest = [ASIHTTPRequest requestWithURL:url];
[newRequest setDidFinishSelector:#selector(getFacebookPhotoFinished:)];
[newRequest setDelegate:self];
[newRequest startAsynchronous];
}
- (void)getFacebookProfileFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"Got Facebook Profile: %#", responseString);
NSString *likesString;
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSArray *interestedIn = [responseJSON objectForKey:#"interested_in"];
if (interestedIn != nil) {
NSString *firstInterest = [interestedIn objectAtIndex:0];
if ([firstInterest compare:#"male"] == 0) {
[_imageView setImage:[UIImage imageNamed:#"depp.jpg"]];
likesString = #"dudes";
} else if ([firstInterest compare:#"female"] == 0) {
[_imageView setImage:[UIImage imageNamed:#"angelina.jpg"]];
likesString = #"babes";
}
} else {
[_imageView setImage:[UIImage imageNamed:#"maltese.jpg"]];
likesString = #"puppies";
}
NSString *username;
NSString *firstName = [responseJSON objectForKey:#"first_name"];
NSString *lastName = [responseJSON objectForKey:#"last_name"];
if (firstName && lastName) {
username = [NSString stringWithFormat:#"%# %#", firstName, lastName];
} else {
username = #"mysterious user";
}
_textView.text = [NSString stringWithFormat:#"Hi %#! I noticed you like %#, so tell me if you think this pic is hot or not!",
username, likesString];
[self refresh];
}
But here am suffered from following error
here in Console i got an error : Got Facebook Photo: {"error":{"message":"(#803) Some of the aliases you requested do not exist: (null)","type":"OAuthException"}}
I tried this by changing various App ID but my problem doesn't solve.
Anyone help me to achieve this.........
Thanks In advance...
You try like this,
NSData *imagedata = UIImageJPEGRepresentation(urPhoto, 10);
[newRequest setPostValue:imagedata forKey:#"data"];
or add image like this,
[newRequest setPostValue:link forKey:#"data"];

How to know if data is present in url are not

I have written code like this but I can't understand how to find if the data is present or not in the URL. Can anyone help me in solving this problem?
Note: This code terminates when the loop is entering the second condition. That is where it's terminating.
-(void)getdetails
{
NSLog(#"in get details");
NSURL *jsonurl=[NSURL URLWithString:#"http://www.myappdemo.com/checkout/services/getonlineusers.php"];
NSMutableURLRequest *request=[[[NSMutableURLRequest alloc]init ]autorelease];
[request setURL:jsonurl];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *serverReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *replyString = [[NSString alloc] initWithBytes:[serverReply bytes] length:[serverReply length] encoding: NSASCIIStringEncoding];
if([replyString isEqualToString:#"Invalid."]){ // i have not set the php code to output "invalid" so this will not work for now ...
NSLog(#"%#",replyString);
}
else {
NSMutableArray *tempArray =[replyString JSONValue];
int count=0;
self.temparray=tempArray;
for(int i=0;i<[tempArray count];i++)
{
///////Here in this loop when it is entering it is terminating /////////
NSDictionary *dict=[tempArray objectAtIndex:i];
NSLog(#"DICT is %#",dict);
NSString *string=[dict objectForKey:#"profilepic"];
NSURL *finalURL = [NSURL URLWithString:[string stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSLog(#"encoding string is %#",finalURL);
NSURL *url=[NSURL URLWithString:string];
NSString *source = [NSString stringWithContentsOfURL:finalURL encoding:NSUTF8StringEncoding error:nil];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:url];
NSLog(#"url is %#",url);
NSData *data=[NSData dataWithContentsOfURL:url];
if(!(data==nil))
{
NSLog(#"data is there");
UIImage *image=[[UIImage alloc]initWithData:data];
[self.array addObject:image];
[image release];
}
else {
/*
NSLog(#"if data is null condition block");
UIImage *image=[[UIImage alloc]init];
[self.array addObject:image];
[image release];
*/
}
count=count+1;
NSLog(#"count is %d",count);
}
}
[replyString release];
}
Where does the app terminate and what is the exception? Have you stepped through to see what the array object looks like during each iteration? Is it failing at NSData initWithContentsOfURL? Why don't you issue that as a separate synchronous request and test to see if you got a response?
Regarding your first (and any subsequent) synchronous request, it would probably be good to add a check to ensure you received a valid response (sorry for the formatting, the code tag isn't playing nicely at the moment)
if (response!=nil) {if([response isKindOfClass:[NSHTTPURLResponse class]]) {
// you have a valid response }}