使用 Alamofire 从 Google 和 Swift 做空 URL

Using Alamofire to get short URL from Google with Swift

我正在尝试在我的应用程序中添加短 url 作为用户的工具,这是 this answer 附带的,不幸的是它没有用! :

import AFNetworking

let googleShortURLKey = "MYKEY"

func getShortURLFromGoogle(longURL: String) {
    let manager = AFHTTPSessionManager()
    manager.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer
    let params = [ "longUrl": longURL ]

    manager.POST("https://www.googleapis.com/urlshortener/v1/url?key=\(googleShortURLKey)", parameters: params, success: {
        (operation: AFHTTPRequestSerializer!,responseObject: AnyObject!) in
        if let responseObject = responseObject as? NSDictionary {
            self.shortURL = responseObject["id"] as? String //That's what you want
        }
    },
                 failure: { (operation: AFHTTPRequestSerializer!,error: NSError!) in
                    print("Error while requesting shortened: " + error.localizedDescription)
    })
}

我已经使用 Alamofire 框架解决了你的问题:

import UIKit
import Alamofire


class ShortURLToolViewController: UIViewController {


    let googleShortURLApiWithKey = "https://www.googleapis.com/urlshortener/v1/url?key=YOURKEY"
    var finalShortURL: String? // To save the short url

    override func viewDidLoad() {
        super.viewDidLoad()
        getShortURLFromGoogle(longURL: "https://github.com/")
    }

    func getShortURLFromGoogle (longURL: String){
        let params = ["longUrl": longURL]

        Alamofire.request(googleShortURLApiWithKey, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { responds in

            if let JSON = responds.result.value {
                print(JSON)
                let json = try? JSONSerialization.jsonObject(with: responds.data!, options: [])
                if let dictionary = json as? [String: Any] {
                    if let shortURL = dictionary["id"] as? String {
                        // access individual value in dictionary
                        self.finalShortURL = shortURL
                        print(self.finalShortURL ?? "NO DATA!")
                    }
                }
            }
        }
    }

}//Class Ends