iOS 解析短链接

February 09, 2017

let urlString = "" // 短链接地址

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()

/* 

Tip:为了安全,最好设置下 User-Agent

let xHTTPAdditionalHeaders: [NSObject: AnyObject] = ["User-Agent": UserAgent.userAgentString]
                     
configuration.HTTPAdditionalHeaders = xHTTPAdditionalHeaders

*/ 

let session = NSURLSession(configuration: configuration)

let task = session.dataTaskWithRequest(NSURLRequest(URL: scanString.urlValue!), completionHandler: { (data, response, error) in
    print("短链接解析 error :\(error)")
                
    dispatch_async(dispatch_get_main_queue(), {
        if error == nil {
            if let str = response?.URL?.absoluteString { // 解析后的长链接
                // 成功操作
            } else {
                // 失败操作
            }
        } else {
            // 失败操作
        }
    })
})
task.resume()