swift基础值网络请求
2016-06-15 22:17
417 查看
NSURLSessionDownloadDelegate
class ViewController: UIViewController, NSURLSessionDownloadDelegate {
var session = NSURLSession()
@IBOutlet weak var imagen: UIImageView!
@IBOutlet weak var progreso: UIProgressView!
@IBAction func cargar(sender: UIButton) {
let imageUrl: NSString = "http://c.hiphotos.baidu.com/image/pic/item/8cb1cb13495409235fa14adf9158d109b2de4942.jpg"
let getImageTask: NSURLSessionDownloadTask =
session.downloadTaskWithURL(NSURL(string: imageUrl as String)!)
getImageTask.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
let sessionConfig =
NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
print("Download finished")
let downloadedImage = UIImage(data: NSData(contentsOfURL: location)!)
dispatch_async(dispatch_get_main_queue(), {() in
self.imagen.image = downloadedImage
})
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64,totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){
dispatch_async(dispatch_get_main_queue(), {() in
let variable = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
self.progreso.progress = variable
}) }
}
NSURLSession
class ViewController: UIViewController, NSURLSessionDownloadDelegate {
var session = NSURLSession()
@IBOutlet weak var imagen: UIImageView!
@IBOutlet weak var progreso: UIProgressView!
@IBAction func cargar(sender: UIButton) {
let imageUrl: NSString = "http://c.hiphotos.baidu.com/image/pic/item/8cb1cb13495409235fa14adf9158d109b2de4942.jpg"
let getImageTask: NSURLSessionDownloadTask =
session.downloadTaskWithURL(NSURL(string: imageUrl as String)!)
getImageTask.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
let sessionConfig =
NSURLSessionConfiguration.defaultSessionConfiguration()
session = NSURLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL){
print("Download finished")
let downloadedImage = UIImage(data: NSData(contentsOfURL: location)!)
dispatch_async(dispatch_get_main_queue(), {() in
self.imagen.image = downloadedImage
})
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64,totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){
dispatch_async(dispatch_get_main_queue(), {() in
let variable = Float(totalBytesWritten)/Float(totalBytesExpectedToWrite)
self.progreso.progress = variable
}) }
}
NSURLSession
import UIKit class ViewController: UIViewController { @IBOutlet weak var city: UILabel! @IBOutlet weak var temperatureCelsius: UITextField! @IBOutlet weak var temperatureCelsiusMax: UITextField! @IBOutlet weak var temperatureCelsiusMin: UITextField! @IBOutlet weak var temperatureKelvin: UITextField! @IBOutlet weak var temperatureKelvinMax: UITextField! @IBOutlet weak var temperatureKelvinMin: UITextField! @IBOutlet weak var humidity: UITextField! @IBOutlet weak var wind: UITextField! override func viewDidLoad() { super.viewDidLoad() let sessionConfig: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() sessionConfig.allowsCellularAccess = false //only accept JSON answer sessionConfig.HTTPAdditionalHeaders = ["Accept":"application/json"] //timeouts and connections allowed sessionConfig.timeoutIntervalForRequest = 30.0 sessionConfig.timeoutIntervalForResource = 60.0 sessionConfig.HTTPMaximumConnectionsPerHost = 1 //create session, assign configuration let session = NSURLSession(configuration: sessionConfig) session.dataTaskWithURL(NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=Barcelona,es&appid=2de143494c0b295cca9337e1e96b00e0")!, completionHandler: {(data, response, error) in let dic:NSDictionary = (try? NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions(rawValue: 0))) as? NSDictionary ?? [String:String]() if dic.count == 0 { return } print(dic) let city: NSString = (dic["name"] as! NSString) let kelvin: AnyObject! = (dic["main"] as! NSDictionary) ["temp"] let kelvin_min: AnyObject! = (dic["main"] as! NSDictionary) ["temp_min"] let kelvin_max: AnyObject! = (dic["main"] as! NSDictionary) ["temp_max"] let celsius = kelvin as! Float - 274.15 as Float let celsius_min = kelvin_min as! Float - 274.15 as Float let celsius_max = kelvin_max as! Float - 274.15 as Float let humidity: AnyObject! = (dic ["main"] as! NSDictionary) ["humidity"] let wind: AnyObject! = (dic ["wind"] as! NSDictionary) ["speed"] //original thread dispatch_async(dispatch_get_main_queue(), { () in self.city.text = "\(city)" self.temperatureCelsius.text = "\(celsius)" self.temperatureCelsiusMax.text = "\(celsius_max)" self.temperatureCelsiusMin.text = "\(celsius_min)" self.temperatureKelvin.text = "\(kelvin)" self.temperatureKelvinMax.text = "\(kelvin_max)" self.temperatureKelvinMin.text = "\(kelvin_min)" self.humidity.text = "\(humidity)" self.wind.text = "\(wind)" }) }).resume() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
相关文章推荐
- ASIHTTPRequest的使用——同步或异步请求
- DES 3DES AES学习总结
- 论文解析:人脸检测中级联卷积神经网络的联合训练
- HTTP,TCP,Socket
- [转]Windows网络编程学习-面向连接的编程方式
- HttpClient模式下的Post方法,可以中文显示
- HttpURLConnection的用法
- 【复习】servlet之Http状态码
- 【复习】servlet之HttpServletResponse
- Android Studio无法使用Apache的HttpClient
- TCP/IP指南
- 子网划分的两个例子
- IP地址、子网掩码、网络号、主机号、网络地址、主机地址
- 详解网络传输中的三张表,MAC地址表、ARP缓存表以及路由表
- OKHTTP通信使用(三)HTTPS
- HTTP状态码详解
- 关于 包、帧、数据报、段和消息 的概念区别
- HTTP协议使用cookie
- 使用HttpURLConnection请求XML数据
- OKHttp通信使用(二)