Saturday 14 September 2013

UITextField and NSURL URLWithString

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
#define TranslateText [NSURL URLWithString:
@"https://translate.yandex.net/api/v1.5/tr.json/translate?key=apikey&lang=en-es&text=To+be,+or+not+to+be%3F"]
//2
#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];
[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`
I want to add a text field into the interface so that a user can type in
their own text to be translated, and I have put in a text field, and
connected it to ViewController.h, as IBOutlet UITextField *textfield;
I am not sure how to implement the button, but when I change the NSURL
URLWithString section in my ViewController .m file to
#define TranslateText [NSURL URLWithString:
@"https://translate.yandex.net/api/v1.5/tr.json/translate?apikeyes&text=To+be,+or+not+to+be%3F":[textfield.text]],
I get the error No Known class method for selector 'URLWithString::'. How
do I properly implement the text field and button?

No comments:

Post a Comment