加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift基础值网络请求

发布时间:2020-12-14 06:54:24 所属栏目:百科 来源:网络整理
导读:NSURLSessionDownloadDelegate class ViewController: UIViewController,NSURLSessionDownloadDelegate { var session = NSURLSession() @IBOutlet weak var imagen: UIImageView! @IBOutlet weak var progreso: UIProgressView! @IBAction func cargar(send


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,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()
    }
    
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读