微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swift网络请求的相关方法

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("下载完成")

ottom:0px; line-height:normal; font-family:Helvetica; color:rgb(69,didWriteData bytesWritten: Int64,totalBytesWritten: Int64,totalBytesExpectedToWrite: Int64)

{

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

ottom:0px; line-height:normal; font-family:Helvetica; color:rgb(69,didResumeAtOffset fileOffset: Int64,expectedTotalBytes: Int64)

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.

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐