在swift 5中将短URL转换为完整URL

  • 本文关键字:URL 转换 swift xcode swift5
  • 更新时间 :
  • 英文 :


你好,我正在尝试将一个短URL如https://goo.gl/maps/MoaZNS825rpixfKu5转换为其原始URL https://www.google.com/maps/place/WhirlyBall+Twin+Cities/@44.8508658,-93.2389179,17z/data=!3m1!4b1!4m5!3m4!1s0x87f62f7bd688277b:0xc0ec9f7b1ccd0da8!8m2!3d44.8510743!4d-93.2366811?hl=en-US

我在类似的旧帖子中找到了一些解决方案,但它们不适用于Xcode 12.4

我尝试使用下面的代码,但它没有返回任何值,当我试图打印expandedURL

let shortURL = "https://goo.gl/maps/MoaZNS825rpixfKu5"
func performRequest(urlString: String){
let urlString = shortURL
let url = URL(string: urlString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "HEAD"
URLSession.shared.dataTask(with: urlRequest) { (data, urlResponse, error) in
    let expandedURL = urlResponse?.url?.absoluteString
    print("expandedURL HEAD: (expandedURL ?? "Oops, not URL")")
}
.resume()
}

我设法让它与下面的代码工作我知道这是一种原始的方式,但它对我来说很有效:)

let shortURL = //"https://goo.gl/maps/MoaZNS825rpixfKu5"
"https://goo.gl/maps/xNdKp1Q1KqFeWQv99"
performRequest (urlString: shortURL)
func performRequest(urlString: String){
if let url = URL(string: urlString){
let session = URLSession(configuration: .default)
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "HEAD"
let task = session.dataTask(with: urlRequest, completionHandler: handle(data:response:error:))
task.resume()
}
}

func handle (data: Data?, response: URLResponse?, error: Error?){
if error != nil {
    print (error)
    return 
}
if let safeData = data {
    let dataString = String(data: safeData, encoding: .utf8)
    let expandedURL = response?.url?.absoluteString
    print(expandedURL!)
}
}

相关内容

  • 没有找到相关文章

最新更新