我在ios中构建了一个翻译应用程序。该应用程序使用Yandex转换API。我遵循了本教程:http://www.raywenderlich.com/5492/working-with-json-in-ios-5 我的ViewController.m看起来像这样(我取出了我的api密钥):
#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`
当我运行应用程序时,我在这行代码中收到错误线程1:信号SIGABRT : 返回UIApplicationMain(argc,argv,nil,NSStringFromClass([AppDelegate class])); 我该怎么办?
答案 0 :(得分:1)
代码中的错误是在那里使用冒号。你应该有这条线......
[NSURL URLWithString: [NSString stringWithFormat: @"https://translate.yandex.net/api/v1.5/tr.json/translate?apikeyes&text=%@", textfield.text];
另外,我不知道你为什么要做#define
。抓取处理按钮的方法中的信息。
NSURL * translateURL = [NSURL URLWithString: [NSString stringWithFormat: @"https://translate.yandex.net/api/v1.5/tr.json/translate?apikeyes&text=%@", textfield.text];