![](/img/trans.png)
[英]How do you know which string to provide as a selector for Swift functions?
[英]How do you know which FBRequest initiated the request didLoad: method?
从facebook iOS API文档中,我创建了两个方法,用于从图中请求好友列表,或者有关当前登录用户的详细信息。
- (IBAction)showMyFriends:(id)sender {
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[[delegate facebook] requestWithGraphPath:@"me/friends" andDelegate:self];
NSLog(@"Getting friends list");
}
- (IBAction)showMyDetails:(id)sender {
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[[delegate facebook] requestWithGraphPath:@"me" andDelegate:self];
NSLog(@"Getting my info");
}
到目前为止听起来很合理。 响应这些调用的委托方法是:
- (void)request:(FBRequest *)request didLoad:(id)result
{
NSLog(@"Got a request");
// Print out friends
// NSArray * items = [NSArray alloc];
// items = [(NSDictionary *)result objectForKey:@"data"];
// for (int i=0; i<[items count]; i++) {
// NSDictionary *friend = [items objectAtIndex:i];
// long long fbid = [[friend objectForKey:@"id"]longLongValue];
// NSString *name = [friend objectForKey:@"name"];
// NSLog(@"id: %lld - Name: %@", fbid, name);
// }
// Print out self username
NSString *username = [result objectForKey:@"name"];
NSLog(@"Username is %@", username);
helloGreeting.text = [NSString stringWithFormat:@"Hello %@", username];
}
问题 :在didLoad
,如何检查当前调用与哪个图形请求相关? 例如,在上面的代码中,我要么打印好友列表,要么打印出用户名,所以我想图像我需要根据请求类型将代码包装在某些case / switch语句中。
我在API上找不到任何明显的东西,确保只执行相关响应代码的最佳方法是什么?
如上所述,您可以检查请求对象以检查生成响应的请求。 您可以使用请求对象的url属性来更方便地检查使用了哪个请求。
例如,获取朋友列表的请求
[facebook requestWithGraphPath:@"me/friends" andDelegate:self];
您可以检查请求对象的URL是:
https://graph.facebook.com/me/friends
请求的以下实现didLoad将检测朋友列表请求并迭代每个朋友。
- (void)request:(FBRequest *)request didLoad:(id)result {
// Friends request
if([request.url rangeOfString:@"me/friends"].location != NSNotFound) {
NSArray *friends = [result objectForKey:@"data"];
for (int i=0;i<friends.count;i++) {
NSDictionary *friend = [friends objectAtIndex:i];
//NSLog([friend objectForKey:@"name"]);
}
}
}
这就是你在“didLoad”中获得FBRequest变量的原因。 您可以使用它来检查原始请求。 这是一种垃圾解决方案,但至少你可以检查它是什么。
实际上看起来像Hackbook正在做一个基于名为“currentAPICall”的int的开关,为每个请求设置一个int,然后在返回中检查它。 所以这一切都是在主线程中完成的,我猜。
我也有不同类型的结果对象。 我最终查看结果并确定它是来自/我的请求还是来自/ home。 我有各种各样的“ifs”看着返回的对象。 无论如何都不理想。 即
if([result objectForKey:@"first_name"]){
// back from getMe()
}
if ([result objectForKey:@"data"]) {
// more checking here- I have two calls that return a data object
}
更新:这不适用于异步请求,其中大多数是,所以我使用上面的方法,检查request.url,而不是像魅力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.