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

swift网络请求的相关方法

发布时间:2020-12-14 01:31:38 所属栏目:百科 来源:网络整理
导读:import UIKit class DownLocader: NSObject,NSURLSessionDownloadDelegate { var session: NSURLSession? override init() { super.init() let imageURL = NSURL(string: "https://httpbin.org/image/png")! session = NSURLSession(configuration: NSURLSes

import UIKit


class DownLocader: NSObject,NSURLSessionDownloadDelegate {

var session: NSURLSession?

override init() {

super.init()

let imageURL = NSURL(string: "https://httpbin.org/image/png")!

session = NSURLSession(configuration: NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("taask"),delegate: self,delegateQueue: nil)

session?.downloadTaskWithURL(imageURL).resume()

}

func URLSession(session: NSURLSession,downloadTask: NSURLSessionDownloadTask,didFinishDownloadingToURL location: NSURL){

print("下载完成")

{

print("正在下载 (totalBytesWritten)/(totalBytesExpectedToWrite)")

print(" (fileOffset) 处恢复下载,一共 (expectedTotalBytes)")

}

class ViewController: UIViewController {

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view,typically from a nib.

//网络请求

var dow: DownLocader

dow = DownLocader()

if let url = NSURL(string: "https://httpbin.org/get"){

NSURLSession.sharedSession().dataTaskWithURL(url

,completionHandler: { (let data,let Response,let error) -> Void in

print(Response)

}).resume()

}

// NSURLSession.sharedSession().downloadTaskWithURL(imageURL) {Loca,response,error) -> Void in

//

//

// guard let url = Loca else { return }

// guard let imageData = NSData(contentsOfURL: url) else { return }

// guard let image = UIImage(data: imageData) else { return }

//

// }.resume()

NSURLSession.sharedSession().downloadTaskWithURL(imageURL) { (Loca,69)"> guard let url = Loca else { return }

guard let imageData = NSData(contentsOfURL: url) else { return }

guard let image = UIImage(data: imageData) else { return }

dispatch_async(dispatch_get_main_queue(),{ () -> Void in

self.imageView.image=image;

})

}.resume()

let uploadURL = NSURL(string: "https://httpbin.org/image/png")!

let request = NSURLRequest(URL: uploadURL)

let fileURL = NSURL(fileURLWithPath: "pathToUpload")

NSURLSession.sharedSession().uploadTaskWithRequest(request,fromFile: fileURL) { (let data,69)"> print("上传成功响应(Response)")

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

(编辑:李大同)

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

    推荐文章
      热点阅读