iOS上で短縮URLを使いたくなったので,短縮URLサービスを色々と調べてみた.
実は短縮URL系のサービスはAPIを提供しているところが多く,そのAPIのURLを叩けば割と簡単に短縮URLを生成できる.
でもこれ,自分で通信部分を書くのって結構めんどくさい気がする.
というわけで,URLShortenerというのを使ってみた.
theaudience/URL-Shortener · GitHub
- cli.gs
- redir.ec
- bit.ly
- is.gd
この中から好きなサービスを選んで短縮URLが得られる.
ただし,is.gd以外は認証が必要になるので,自分でアカウントを発行しておく必要がある.
というわけで,今回はis.dgを使ってみた.
cocoapodsにする
ライブラリの管理はすべてcocoapodsでやりたかった.
theaudience/URL-Shortener · GitHub
ここには残念ながらcocoapodsの導入方法も書いてなく,cocoapodsに登録もされていないようだった.
仕方ないのでcocoapods化しておいた.
Podfileに以下の一文を追記するとインストールできる.
pod 'UrlShortener', git: "https://github.com/h3poteto/URL-Shortener.git"
使い方
var shortener = UrlShortener() shortener.shortenUrl(longURL, withService: UrlShortenerServiceIsgd, completion: { (shortUrl) -> Void in // hogehoge }, error: { (error) -> Void in // hogehoge })
割と楽にいける!!
と思いきや,たまにうまく行かないことがあります.
Sorry, the URL you entered is on our internal blacklist. It may have been used abusively in the past, or it may link to another URL redirection service.
実はこれ一度is.gdで短縮したURLが,再びis.gdで短縮されるときに発生します.
つまりは,短縮URL化が二重で走っているんですね.
しかもこれ,shortenUrlメソッドのブロックでは,completeブロックとして扱われています.
なので,ちゃんとチェックしてやる必要があります.
var shortener = UrlShortener() shortener.shortenUrl(longURL, withService: UrlShortenerServiceIsgd, completion: { (shortUrl) -> Void i if shortUrl.hasPrefix("http://") || shortUrl.hasPrefix("https://") { // 成功時の処理 } else { // 二重に短縮化が走っている } }, error: { (error) -> Void in // hogehoge })