使用同步Post请求,同步获取IP地址的信息
//
// ViewController.swift
// Dome2test
//
// Created by 郭文亮 on 2018/11/21.
// Copyright © 2018年 finalliang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
label.frame = CGRect(x: 20, y: 40, width: 280, height: 500)
label.text = "loading..."
label.font = UIFont(name: "Arial", size: 12)
label.backgroundColor = UIColor.lightGray
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
self.view.addSubview(label)
let url = URL(string: "http://ip.taobao.com/service/getIpInfo.php?ip=63.223.108.42")
var request = URLRequest.init(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
//设置网络通信方式为Post 默认为get post相对来说传递数量更大,更安全。但效率相对低一些
request.httpMethod = "POST"
//初始化一个信号量 为0。实现同步效果
let semaphore = DispatchSemaphore(value: 0)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {(data,response,error)
-> Void in
if error != nil {
print(error.debugDescription)
}else{
let result = String(data: data!, encoding: String.Encoding.utf8)
DispatchQueue.main.async(execute: {() -> Void in
self.label.text = result
})
}
semaphore.signal()
})
task.resume()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
通过异步POST请求获取ip地址的信息
// ViewController.swift
// Dome2test
//
// Created by 郭文亮 on 2018/11/21.
// Copyright © 2018年 finalliang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var label = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
label.frame = CGRect(x: 20, y: 40, width: 280, height: 500)
label.text = "loading..."
label.font = UIFont(name: "Arial", size: 12)
label.backgroundColor = UIColor.lightGray
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
self.view.addSubview(label)
let url = URL(string: "http://ip.taobao.com/service/getIpInfo.php?ip=63.223.108.42")
var request = URLRequest(url: url!, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30)
request.httpMethod = "POST"
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: {(data,response,error)
-> Void in
if (error != nil){
print(error.debugDescription)
}else{
let result = String(data: data!, encoding: String.Encoding.utf8)
DispatchQueue.main.async(execute: {() -> Void in
self.label.text = result
})
}
})
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}