Swift3.0 UrlSession

作者: 贝尔特伦 | 来源:发表于2016-09-28 14:30 被阅读1891次

    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的对象。

    相关文章

      网友评论

        本文标题:Swift3.0 UrlSession

        本文链接:https://www.haomeiwen.com/subject/highyttx.html