Swift3.0 UrlSession

GET请求

class func zyGETWithURLSession(_ urlString:String,parmas:NSDictionary,mathFunction:@escaping (_ responObject:AnyObject)->Void){

    let session = URLSession.shared;
    let str = self.parmasStringWithParmas(parmas);
    let url = URL(string: String(format: "%@?%@", urlString,str));

    let task = session.dataTask(with: url!, completionHandler: { (data, respons, eror) -> Void in
        if data != nil{
            let responsobject = try?JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments);

            mathFunction(responsobject! as AnyObject);
        }else{
            mathFunction("file" as AnyObject);
        }
        
        
    }) 
    task.resume();
    
}

POST请求

class func zyPOSTwithURLSession(_ urlString:String,parmas:NSDictionary,mathFunction:@escaping (_ responObject:AnyObject)->Void){
    
    let session = URLSession.shared;
    
    let str = self.parmasStringWithParmas(parmas);
    let url = URL(string: urlString);
    
    var request = URLRequest(url: url!);
    
    request.httpMethod = "POST";

    request.httpBody = str.data(using: String.Encoding.utf8.rawValue);
    
    let task = session.dataTask(with:request, completionHandler: { (data, respons, error) -> Void in
        
        if data != nil{
            let responsobject = try?JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments);
            
            mathFunction(responsobject! as AnyObject);
        }else{
            mathFunction("file" as AnyObject);
        }
    }) 
    
    task.resume();
}

拼接GET参数

  class func parmasStringWithParmas(_ parmas:NSDictionary)->NSString{

    let parString = NSMutableString();
    let arr = parmas.allKeys as NSArray;
    for i in 0 ..< arr.count{
        let key = arr[i] as! String;
        let value = parmas.object(forKey: arr[i]) as! NSString;
        parString.appendFormat("%@=%@", key,value);
        
        let lastKey = arr.lastObject as! String;
        if (key != lastKey) {
            
            parString.appendFormat("&");
        }

        
    }
    return parString;
}

设置请求头

request.setValue(fileType, forHTTPHeaderField: "Content-Type");

上传方法

class func uploadFile(_ urlString:String,_ fileType:String,_ filePath:String,_ mathFunction: @escaping zymathFuncation){
    let session = URLSession.shared;
    let url = URL.init(string: urlString);
    
    var request = URLRequest(url: url!);
    request.httpMethod = "POST";
    request.setValue(fileType, forHTTPHeaderField: "Content-Type");
    
    let filedata:Data = try!Data.init(contentsOf: URL.init(fileURLWithPath: filePath));

    let task = session.uploadTask(with: request, from: filedata) { (data, response, error) in
        

    }
    task.resume();
}

删除方法

class func deletFile(urlString:String,_ mathFunction: @escaping zymathFuncation){
    let session = URLSession.shared;
    let url = URL(string: urlString);
    var request = URLRequest(url: url!);
    request.httpMethod = "DELETE";
    let task = session.dataTask(with:request, completionHandler: { (data, respons, error) -> Void in
        

    })
    
    task.resume();
}

更新方法

class func zyUpwithURLSession(_ urlString:String,parmas:Dictionary<String,Any>,mathFunction:@escaping (_ responObject:AnyObject,_ isSuccess:Bool,_ zyError:Error?)->Void){

    let session = URLSession.shared;
    let url = URL(string: urlString);
    var request = URLRequest(url: url!);
    request.httpMethod = "PUT";
    let jsonData = try?JSONSerialization.data(withJSONObject: parmas, options: JSONSerialization.WritingOptions.prettyPrinted);
    request.httpBody = jsonData! as Data;
   
    let task = session.dataTask(with:request, completionHandler: { (data, respons, error) -> Void in
        

    })

    task.resume();
}

DownLoad任务

//
//  ZYSessionDownload.swift
//  NSURLSession
//
//  Created by mac on 16/9/10.
//  Copyright © 2016年 ZY. All rights reserved.
//

import UIKit

class ZYSessionDownload: NSObject ,URLSessionDownloadDelegate{

var zySession:Foundation.URLSession?;
class func shareInstance()->ZYSessionDownload{
    let sessiondown = ZYSessionDownload();
    return sessiondown;
}

/**
 download
 */

 func zyDownLoadWithURLSession(_ urlString:String,parmas:NSDictionary,mathFunction:(_ responObject:AnyObject)->Void){

    let configer = URLSessionConfiguration.default;
    let session = Foundation.URLSession(configuration: configer, delegate: self, delegateQueue: OperationQueue.main);
    
    zySession = session;
    
    let str = self.parmasStringWithParmas(parmas);
    let url = URL(string: urlString);
    
    if (parmas.allKeys.count > 0){
        
        var request = URLRequest(url: url!);
        
        request.httpMethod = "POST";
        
        request.httpBody = str.data(using: String.Encoding.utf8.rawValue);
        let task = session.downloadTask(with: request, completionHandler: { (url, respons, error) -> Void in
            
            
        })
        
        task.resume();
    }else{
        let task = session.downloadTask(with: url!, completionHandler: { (locationUrl, respons, error) -> Void in
            let path = "Users/mac/Desktop/ss.pdf";
            try!FileManager.default.moveItem(at: locationUrl!, to: URL(fileURLWithPath: path));
        }) 
        
        task.resume();
    }
    
}


//下载完成时调用
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL){
    
}

//下载时调用
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64){
    
}
//任务完成时调用
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64){
    
}
//拼接GET参数
func parmasStringWithParmas(_ parmas:NSDictionary)->NSString{
    
    let parString = NSMutableString();
    let arr = parmas.allKeys as NSArray;
    for i in 0 ..< arr.count{
        let key = arr[i] as! String;
        let value = parmas.object(forKey: arr[i]) as! NSString;
        parString.appendFormat("%@=%@", key,value);
        
        let lastKey = arr.lastObject as! String;
        if (key != lastKey) {
            
            parString.appendFormat("&");
        }
        
        
    }
    return parString;
}


}

注意,3.0以后,session不能使用NSRequest和NSMutableRequest的对象。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,973评论 19 139
  • 因为iOS的权限限制, 如果使用HTTP协议要配置info.plist, 将Allow Arbitary Load...
    brycegao阅读 1,925评论 0 4
  • 218.241.181.202 wxhl60 123456 192.168.10.253 wxhl66 wxhl6...
    CYC666阅读 1,443评论 0 6
  • 1.原型链。2.构造函数。3.组合继承。4.寄生组合继承。5.原型式。6.寄生式。 1、简单原型链: 核心:拿父类...
    overflow_hidden阅读 712评论 0 0
  • (445) 杰弟想要去迦南音乐学校上个暑期班,但是我查了一下价格,三个月八千呢,太贵啦,所以他要是知道了就未必会去...
    韩尚小阅读 268评论 1 1