我一直在四处寻找,看过类似的帖子,但是没有这样可以给我答案。这是我的应用程序设置和流程:
问题:除了我从Facebook获得的FBID之外,一切都返回NULL。但是,如果我从Facebook注销然后登录,那就是它的工作原理。
这是我的代码:
viewDidAppear方法:
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:NO];
if (FBSession.activeSession.isOpen) {
[self populateUserDetails];
}
//Connect to WebService
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://atnightcorp.com/api/member/id/%@/format/json", fbid]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection connectionWithRequest:request delegate:self];
NSArray *pics = [member valueForKeyPath:@"photos"];
NSString *picCount = [NSString stringWithFormat:@"%d", [pics count]];
[photosCount setTitle:picCount forState:UIControlStateNormal];
NSLog(@"PHOTO: %@", picCount);
NSLog(@"FB: %@", fbid);
}
我尝试在viewDidLoad中放置NSURL请求和连接代码,但后来我没有收到任何回复。
我的NSURLConnection方法:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc]init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
[data appendData:theData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
member = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"The download could not complete. Please make sure you are connected to internet" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[errorView show];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
您在上面看到的populateUserDetails方法:
- (void)populateUserDetails
{
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
self.userProfileImage.profileID = user.id;
self.navigationItem.title = user.name;
self.fbid = user.id;
}
}];
}
}
此方法基本上在用户登录后设置FBID。您应该知道的其他重要事项可以帮助您了解我的项目:
请帮助,因为我一直在寻找过去3天的答案。
答案 0 :(得分:0)
你的问题是populateUserDetails
被调用并返回而不等待代码被执行(因为它是一个带有completition处理程序的异步任务,并且当你第一次调用NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://atnightcorp.com/api/member/id/%@/format/json", fbid]];
时,fbid
无法正确设置(或者self.fbid
而不是fbid
,因为fbid
是属性)。
因此,您应该尝试将处理viewDidAppear
请求的整个代码移动到一个单独的方法中,然后在使用startWithCompletionHandler
设置行后从self.fbid = user.id
调用该方法
也请使用[super viewDidAppear:animated];
param调用NO
(这不会解决您的问题,但这是正确的方法)