Swift-AFNetworking 使用实例

前端之家收集整理的这篇文章主要介绍了Swift-AFNetworking 使用实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

创建httpTool.swift 网络请求工具类

import UIKit
//请求方法
/// - GET: get
/// - POST: post
enum RequsetMethod:String {
    case GET = "GET"
    case POST =  "POST"
}

class httpTool: AFHTTPSessionManager {

    //单例
    static let sharedTools:httpTool = {
        let instance = httpTool()
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
     // 定义请求完成的回调的别名
    typealias httptoolBack = (response:AnyObject?,error:NSError?)->()

    /// 请求数据
    ///
    /// - parameter urlString: 请求地址
    /// - parameter parameters: 请求参数
    /// - parameter finished: 请求成功或者失败的回调

    func request(method: RequsetMethod = .GET,urlString: String,parameters: AnyObject?,finished:httptoolBack){

        // dataTaskWithHttp 是写在 .m 文件里面的
        // 对应在 Swift 中的,就是 private 修饰的方法

        // 定义请求成功的闭包
        let success = { (dataTask: NSURLSessionDataTask,responSEObject: AnyObject?) -> Void in
            finished(response: responSEObject,error: nil)
        }

        // 定义请求失败的闭包
        let failure = { (dataTask: NSURLSessionDataTask?,error: NSError) -> Void in
            finished(response: nil,error: error)
        }

        if method == .GET {

            GET(urlString,parameters: parameters,progress: nil,success: success,failure: failure)
        }else{
            POST(urlString,failure: failure)
        }
    }




    /// 发送请求(上传文件)

    func requestWithData(data: NSData,name: String,finished:httptoolBack) {
        // 定义请求成功的闭包
        let success = { (dataTask: NSURLSessionDataTask,error: error)
        }

        POST(urlString,constructingBodyWithBlock: { (formData) -> Void in
            formData.appendPartWithFileData(data,name: name,fileName: "aa",mimeType: "application/octet-stream")
            },failure: failure)
    }
}

发送post请求

//创建httpTool 实例
        let TabHttpTool = httpTool.sharedTools
        //创建请求参数
        let params = ["username":"invest","password":"123456"]
        //发送psot请求
        TabHttpTool.request(RequsetMethod.POST,urlString: "http://api....../login",parameters: params) { (response,error) in
            print(response)
        }

服务器返回结果

如有疑问联系QQ2584779025
GitHub https://github.com/JamesWangBJ/testTableSwift.git 相互学习,如有错误多多指教

原文链接:https://www.f2er.com/swift/323739.html

猜你在找的Swift相关文章