エラーハンドリングしてないのでもうちょいちゃんと書かないといけない。
googleの短縮URLのAPIKeyを入れれば使えます。
因みに認証用のURLとかってgoogleの短縮URLだと短縮できないんですね…。
extension String {
func shortURL(success:(shortedUrl:NSURL)->()){
let apiKey = "AIzaSyBLOTjWpximy4FF9q0V-hKoaqjlo2KNwi4"
let url = "https://www.googleapis.com/urlshortener/v1/url?key="
let request = NSMutableURLRequest(URL: NSURL(string: url+apiKey)!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10.0)
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPBody = "{\"longUrl\": \"\(self)\"}".dataUsingEncoding(NSUTF8StringEncoding)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
print(error?.localizedDescription)
}else{
print(String(data: data!, encoding: NSUTF8StringEncoding))
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
if let status = json as? Dictionary<String,String>{
success(shorted: status["id"]!)
}
}
}.resume()
}
}
使い方
url.shortURL({ (shortedUrl) -> () in
print(shortedUrl)
})
Stringにしたけど、NSURLでもいいかもね