iOS 使用Instagram授权登录

移动端集成Instagram登录授权目前是不支持SDK,需要通过web形式加载url来获取授权信息

1、申请应用

先去https://developers.facebook.com/apps/创建应用,过程比较简单略过。设置完成后进入应用,在控制面板中往下翻会找到Instagram点击设置

这是我添加产品后的

可以看到应用的所有信息,Instagram 应用编号Instagram 应用密钥是自动生成的;Instagram Display 名称自定义;有效 OAuth 跳转 URI需要能正常跳转的网址并且是https开头的,这个后面授权成功会回调跳转;取消授权回调网址数据删除请求网址可以与上面一样。
image.png

往下翻,找到

image.png

添加一名Instagram测试人员(必须添加否则会授权失败)
image.png

到这里Instagram准备工作已经做完了。

2、iOS授权

主要思路就是:通过webView加载获取codeurl,拦截回调的有效 OAuth 跳转 URI获取里面的code值,通过code获取user_idaccess_token,在通过user_idaccess_token获取用户名等信息。

直接上代码:

#import "WebLoginController.h"

@interface InstagramLoginController : WebLoginController

@property (nonatomic, copy) void (^getUserInfoCallback)(BOOL isSuccess, NSDictionary * _Nullable userInfo) ;

@end

#import "InstagramLoginController.h"

#define Instagram_client_id @""
#define Instagram_client_secret @""
#define Instagram_URI @"https://www.baidu.com/"

@interface InstagramLoginController ()

@end

@implementation InstagramLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString *urlString = [NSString stringWithFormat: @"https://api.instagram.com/oauth/authorize?client_id=%@&redirect_uri=%@&scope=user_profile,user_media&response_type=code", Instagram_client_id, Instagram_URI];
    
    [self loadUrl:urlString];
    
}

- (BOOL)judgeUrl:(NSString *)urlString {
    if ([urlString hasPrefix:Instagram_URI]) {
        NSString *replaceString = [NSString stringWithFormat:@"%@?code=", Instagram_URI];
        urlString = [urlString stringByReplacingOccurrencesOfString:replaceString withString:@""];
        NSString *code = [urlString stringByReplacingOccurrencesOfString:@"#_" withString:@""];
        NSLog(@"%@", urlString);
        [self getUserDateWidthCode:code];
        
        return NO;
    }
    NSLog(@"%@", urlString);
    return YES;
}

//处理请求用户数据
- (void)getUserDateWidthCode:(NSString *)code {
    
    NSDictionary *params = @{
        @"client_id": Instagram_client_id,
        @"client_secret": Instagram_client_secret,
        @"grant_type": @"authorization_code",
        @"redirect_uri": Instagram_URI,
        @"code": code,
    };
    
    [PublicDialogManager showWaittingInView:self.view];
    [HTTPMANAGER startPostUrl:@"https://api.instagram.com/oauth/access_token" param:params success:^(NSDictionary * _Nullable resultDict) {
        NSLog(@"%@", resultDict);
        NSString *user_id = [resultDict stringWithFilted:@"user_id"];
        NSString *access_token = [resultDict stringWithFilted:@"access_token"];
        if (user_id.length > 0 && access_token.length > 0) {
            NSString *userInfoUrl = [NSString stringWithFormat:@"https://graph.instagram.com/%@?fields=id,username&access_token=%@", user_id, access_token];
            [HTTPMANAGER startGetUrl:userInfoUrl param:nil success:^(NSDictionary * _Nullable resultDict) {
                [PublicDialogManager hideWaittingInView:self.view];
                NSLog(@"%@", resultDict);
                if (self.getUserInfoCallback) {
                    self.getUserInfoCallback(YES, resultDict);
                }
                [self popBack];
            } failure:^(NSError * _Nullable error) {
                [PublicDialogManager hideWaittingInView:self.view];
                if (self.getUserInfoCallback) {
                    self.getUserInfoCallback(NO, nil);
                }
                NSLog(@"%@", error);
                [self popBack];
            }];
        }else {
            [PublicDialogManager hideWaittingInView:self.view];
            if (self.getUserInfoCallback) {
                self.getUserInfoCallback(NO, nil);
            }
            [self popBack];
        }
    } failure:^(NSError * _Nullable error) {
        [PublicDialogManager hideWaittingInView:self.view];
        if (self.getUserInfoCallback) {
            self.getUserInfoCallback(NO, nil);
        }
        [self popBack];
        NSLog(@"%@", error);
    }];
    
}

- (void)popBack {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end

再上一下WebLoginController部分代码:

@interface WebLoginController : BaseViewController

@property (nonatomic, strong) WKWebView *webView ;
@property (nonatomic, strong) NSString *urlString ;

- (void)loadUrl:(NSString *)urlString ;

@end

#import "WebLoginController.h"

@interface WebLoginController ()

@end

@implementation WebLoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    WKWebViewConfiguration *webConfiguration = [WKWebViewConfiguration new];
    
    WKWebView *webView = [[WKWebView alloc] initWithFrame:[UIScreen mainScreen].bounds configuration:webConfiguration];
    [self.view addSubview:webView];
    webView.navigationDelegate = self;
    webView.opaque = NO;
    webView.backgroundColor = UIColorHex(#f6f6f6);
    self.webView = webView;
    
    [webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(navigationBgView.mas_bottom);
        make.left.right.bottom.mas_equalTo(0);
    }];
    
}

- (void)loadUrl:(NSString *)urlString {
    
    NSString *urlStr = urlString;
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
    [self.webView loadRequest:request];
    
}

//子类重写
- (BOOL)judgeUrl:(NSString *)urlString {
    return YES;
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    // 获取完整url并进行UTF-8转码
    NSString *strRequest = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    if ([self judgeUrl:strRequest]) {
        // 允许跳转
        decisionHandler(WKNavigationActionPolicyAllow);
    }else {
        // 不允许跳转
        decisionHandler(WKNavigationActionPolicyCancel);
    }
}

@end

最后成功获取信息,做一下回调就好了。


image.png

你可能感兴趣的:(iOS 使用Instagram授权登录)