UITextField and NSURL URLWithString - iphone

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

Related

connectionDidFinishLoading shows an errors in the NSString *jsonString line

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError *error = nil;
NSString *jsonString = [[NSJSONSerialization JSONObjectWithData:_buffer options:0 error:&error] description];
dispatch_async(dispatch_get_main_queue(), ^{
if (!error)
{
self.textField.text = jsonString;
}
else
{
self.textField.text = [error localizedDescription];
}
[self.spinner stopAnimating];
[self.fetchButton setEnabled:YES];
self.connection = nil;
self.buffer = nil;
});
});
}
When i write this method then it shows errors in the fifth line. please help me I am new for the Iphone.Thanks in advance.
You should write it like this:
NSString *jsonString = [[NSJSONSerialization JSONObjectWithData:_buffer options:0 error:&error] description];
Remove amp;
from
NSString *jsonString = [[NSJSONSerialization JSONObjectWithData:_buffer options:0 error:&error] description];
It should be
NSString *jsonString = [[NSJSONSerialization JSONObjectWithData:_buffer options:0 error:&error] description];

Xcode Parse Json Data

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.

Parsing JSON iOS

I'm trying to parse some JSON in iOS to get a URL from google. I've gotten pretty far (see code below), the problem is since I've never worked with JSON before, I'm not really sure how things are defined. How can I look for an object that's inside another object?
For example if I want to get the first unescapedUrl here how can I do that? I tried simply using objectForKey, but it didn't work.. I'm guessing I'm going to have to specify the exact path. How can I do that?
Here's the code I'm using:
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestSearchURL [NSURL URLWithString: #"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=monkey"] //2
#import "ViewController.h"
#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: kLatestSearchURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
// ---------------------------- Will Start Parsing Here ------------------------------
}
#end
God save literals (Xcode 4.5 and iOS 6.0 or later SDK, LLVM Compiler 4.0 required). Deploys back to iOS 5.
NSString *url = resp[#"responseData"][#"results"][0][#"unescapedUrl"];
You can use objectForKey: for dictionaries and objectAtIndex: for arrays:
NSString *url = [[[[resp objectForKey:#"responseData"]
objectForKey:#"results"]
objectAtIndex:0]
objectForKey:#"unescapedUrl"];

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;

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