2015年10月30日 星期五

在iOS App裡加入Fan page與App Store link

Screenshot

在App裡面,我們經常會需要連結到自己的粉絲團,或是App Store頁面請使用者評分。
接下來講解怎麼實做。

連到粉絲團

下面這一段code的思考模式是這樣,我們會先用canOpenURL去檢查使用者是否安裝了Facebook app,
若有則用原生的facebook app開啟粉絲團頁面,若無則使用safari去開啟行動網頁。
如果不知道自己的粉絲團id可以使用 http://findmyfbid.com/ 查詢。

NSURL *facebookAppLink = [NSURL URLWithString:@"fb://profile/yourid"];
NSURL *facebookURL = [NSURL URLWithString:@"https://m.facebook.com/yourid"];

if ([[UIApplication sharedApplication] canOpenURL:facebookAppLink]) {
    [[UIApplication sharedApplication] openURL:facebookAppLink];
} else {
    [[UIApplication sharedApplication] openURL:facebookURL];
}

在iOS9你很可能會遇到這樣的錯誤

CanOpen[2255:1002610] -canOpenURL: failed for URL:
 "fb://" - error: "(null)"

這裡要特別注意的是,在iOS9之後必需要在info.plist裡面設置LSApplicationQueriesSchemes,
這樣canOpenURL才會回傳YES,沒有設定他只會回傳NO。所以要到info.plist裡面加入
LSApplicationQueriesSchemes,新增一個fb item,類別是String,這樣就可以了。

scheme

圖片裡有很多item是因為我有整合facebook登入,如果要打開粉絲團頁面其實只需要fb那個就可以。

App Store頁面

網路上有很多人採用openURL的方式來打開App Store連結,如下所示。
但我個人覺得這個方式打開的速度有點慢,因為它會先打開safari,然後再跳轉到原生App Store裡面,
大概會lag幾秒,使用者體驗不是很優。

NSString *iTunesLink = @"itms://itunes.apple.com/us/app/apple-store/id375380948?mt=8";
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];

其實在iOS6之後就有新增一個SKStoreProductViewController類別可以在App內打開App Store頁面,
不用跳出自己的App就可以讓使用者評分了,這樣感覺是不是好很多了?

首先引入StoreKit,並讓自己的ViewController遵從SKStoreProductViewControllerDelegate。

@import StoreKit;

@interface ViewController : UIViewController<SKStoreProductViewControllerDelegate>
@end

打開頁面

- (void)openAppStorePage
{
    NSString *cAppleID = @"your app id";
    if ([SKStoreProductViewController class]) {
        SKStoreProductViewController *storeViewController = [[SKStoreProductViewController alloc] init];
        storeViewController.delegate = self;
        NSDictionary *dict = [NSDictionary dictionaryWithObject:cAppleID forKey: SKStoreProductParameterITunesItemIdentifier];
        [storeViewController loadProductWithParameters:dict completionBlock:^(BOOL result, NSError * _Nullable error) {
            if (result) {
                [self.navigationController presentViewController:storeViewController animated:YES completion:nil];
            }
        }];
    }

按下關閉時要dismiss目前顯示的頁面。

- (void)productViewControllerDidFinish:(SKStoreProductViewController *)viewController {
    [viewController dismissViewControllerAnimated: YES completion: nil];
}

沒有留言:

張貼留言