簡體   English   中英

你怎么知道哪個FBRequest發起了請求didLoad:方法?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM