iOS 解析短链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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()