Reality Keysと連携するiOSアプリをつくる 第2回 RunKeeper連携
はじめに
今回は契約のセットアップに必要なRunKeeperのユーザーIDを取得します。契約のセットアップについての詳細は過去記事をみてください。
目次
- By My Coin Web版はどうしているか
- iOSでどう実装するか
By My Coin Web版はどうしているか
OAuth連携してます。
index.html
<div class="form-group button-row"> <div class="col-md-12 text-center"> <a id="authenticate-runkeeper-user" type="button" class="btn btn-primary btn-authenticate-runkeeper-user initialized-only">Connect to RunKeeper</a> <a class="btn btn-primary jump-to-secret" href="#section2">Next (set secret)</a> <button id="set-goal-submit" type="submit" class="btn btn-primary set-goal-submit">Set this goal</button> </div> </div>
bymycoins.js
var oracle_base = 'https://www.realitykeys.com' $('#authenticate-runkeeper-user').click( function() { var return_url = location.protocol + '//' + location.host + location.pathname; var url = oracle_base + '/runkeeper/start-auth/' + '?return_url=' + encodeURI(return_url); $(this).attr('href', url); return true; });
iOSでどう実装するか
- 認可完了後、ダミーのURL( http://dummy-return-url.com )にリダイレクトするように設定
- 画面遷移前にURLをチェックして、ダミーのURLであれば画面遷移を行わない。
- ダミーのURLは以下形式になっているのでユーザーIDを取得できる。
URL: http://dummy-return-url.com/?completed_user_id=40442259
func loadRequest() { var originalString = "http://dummy-return-url.com" var customAllowedSet = NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet) let url = NSURL(string: "https://www.realitykeys.com/runkeeper/start-auth/?return_url=" + escapedString!)! let urlRequest = NSURLRequest(URL: url) webView.loadRequest(urlRequest) }
func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool { if request.URL.absoluteString!.rangeOfString("http://dummy-return-url.com") != nil { let comp: NSURLComponents? = NSURLComponents(string: request.URL.absoluteString!) for (var i=0; i < comp?.queryItems?.count; i++) { let item = comp?.queryItems?[i] as NSURLQueryItem let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject(item.value, forKey: "runkeeper_user_id") break } var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("dissmissWalkthrough"), userInfo: nil, repeats: false) return false } return true }
こんな感じ
ログイン画面
認可後
まとめ
次回はiOSから契約のセットアップをやります。