afn的使用 swift
2019-05-24 10:42:00 weixin_33997389 阅读数 6

import UIKit
import AFNetworking

enum WBReqMethod {
    case get
    case post
}

class WBNetworkingManger: AFHTTPSessionManager {

    static let shared : WBNetworkingManger = {
        let manger = WBNetworkingManger()
        manger.responseSerializer = AFHTTPResponseSerializer()
        manger.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return manger
    }()
   

    func request(method:WBReqMethod = .get,urlString:String,prama:[String:AnyObject]?,completion:@escaping (_ jsonString:AnyObject?,_ isSuccess:Bool)->()) {
       
        let successBlock = {(task:URLSessionDataTask,json:Any?) ->() in
            completion(json as AnyObject,true)
        }
       
        let failureBlock = {(task:URLSessionDataTask?,error:Error) ->() in
            completion(nil,false)
        }
       
        if method == .get {
            get(urlString, parameters: prama, progress: nil, success: successBlock, failure: failureBlock)
        }else{
            post(urlString, parameters: prama, progress: nil, success: successBlock, failure: failureBlock)
        }

    }
}

转载于:https://www.jianshu.com/p/af62e16c603a

2017-06-18 16:17:00 weixin_34409357 阅读数 23

看着视频敲swift,人家封装了一个AFN的方法,我跟着封装,结果出错了,原因我目前还不知道,不过我改了下终于改对了,现在贴出来,以后可以自己用,下面是代码:

import UIKit
import AFNetworking


enum WBHTTPMethod {
   case GET
   case Post
}

/// 网络管理工具
///单例
class WBNetworkManger: AFHTTPSessionManager {

/// 静态区/常量/闭包/在第一次访问时,执行闭包,并且将结果保存在shared常量中
static let shared = WBNetworkManger()



func request(method:WBHTTPMethod = .GET,URLString:String,parameters:[String:AnyObject],completion:@escaping (_ json:AnyObject?,_ isSucess:Bool)->()) {
   
    //成功回调
    let sucess = { (task: URLSessionDataTask, json: Any?) in
        completion((json as? [String: Any])! as AnyObject, true)
//            print(json)
    }
    //失败回调
    let failure = { (task: URLSessionDataTask?, error:Error) in
       print("网络请求 \(error)")
        completion(nil, false)
    }
    


    
    if method == .GET {
         get(URLString, parameters: parameters, progress: nil, success: sucess, failure: failure)
    }else {
        post(URLString, parameters: parameters, progress: nil, success: sucess, failure: failure)
    }
   
  }
}

这个里面使用单例进行的封装,相比而言swift的单例比OC的要好写的多,然后request这个函数中我是默认给了GET的请求方法。我再说说我之前改了哪里,就是把sucess里面的json的类型改为了Any?,期初写的是AnyObject,然后再下面的if语句中写的时候,你要穿sucess的时候,会报错,提示你加入一大串我不理解的东西,加入后不报错,但是就是请求不到数据了,控制台输入的是这样的:

2440882-4e9b6e280be42272.png
控制台输出

如图,显示的baseURL是空,原因我不知道,等我明白了,我在练练解释解释!

2016-08-13 16:17:00 weixin_33872660 阅读数 34
1638260-987c46ea4b35f3d6.png
1638260-b3db53f7c1d3ab38.png
1638260-4586bf6cff81cbe2.png
1638260-43781ff9421201c5.png
1638260-c1f4155a551ef92f.png
1638260-c7ad1260f4360804.png
1638260-16efc6061e8fc706.png
1638260-44eec1f93d7d5b90.png
1638260-1ee18f3036947875.png
2018-07-23 17:40:47 u014651417 阅读数 162
import UIKit

class HCNetWork: AFHTTPSessionManager {
    //单利
    staticletsharedTools:HCNetWork= {
        letbaseUrl =NSURL(string:"http://www.51xianchang.com/")!
        letmanager =HCNetWork.init(baseURL: baseUrlasURL, sessionConfiguration:URLSessionConfiguration.default)
        manager.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/html", "text/json", "text/javascript", "text/plain") as? Set
        // 设置请求参数为JSON字符串
        manager.requestSerializer = AFJSONRequestSerializer()
        // 请求超时设定
        manager.requestSerializer.timeoutInterval = 10
        // 设置允许自生成证书
        manager.securityPolicy.allowInvalidCertificates = true
        //设置请求头
        manager.requestSerializer.setValue("APP", forHTTPHeaderField:"loginType")
        manager.requestSerializer.setValue("iOS", forHTTPHeaderField:"deviceType")

        returnmanager
    }()
    typealiasrequestBack = (_response:Any?,_error:Error?) -> ()
}
extension HCNetWork {
   
    funcrequestDictionary(urlString:String, parameters: [String:AnyObject]?, finished:@escapingrequestBack) {

        letsuccess = { (task:URLSessionDataTask?, responseObject:Any?) -> ()in
            finished(responseObject,  nil)
        }
        letfailure = { (task:URLSessionDataTask?, error:Error) -> ()in
            finished(nil,  error)
        }
        post(urlString, parameters: parameters, progress:nil, success: success, failure: failure)
    } 
}

自己写的上传 json 参数网络请求, 拿去可用

2017-06-13 17:05:00 weixin_34015566 阅读数 21

AFN数据请求(swift终极版)

//头文件
import AFNetworking

 //AFN数据请求(swift终极版)
        let manager = AFHTTPSessionManager()
        manager.responseSerializer.acceptableContentTypes?.insert("application/json")
         let path  =  "https://test.kemeiapp.com/outer/v1/video/getVideoType.do"
        let dict = ["sorted":1]
        manager.post(path, parameters: dict, progress:nil, success: {(URLSessionDataTask,responseObject) in
            //转换类型
           let responseObject = responseObject as AnyObject
            
             print("得到数据:\(responseObject)")
            //回到主线程
             if responseObject["code"] as? String == "00" {
                //主线程
                  DispatchQueue.main.async {
                    print("走00成功");
                }
            
            }
            
        }) { (URLSessionDataTask,error) in
            
            print("数据请求失败\(error.localizedDescription)");
            //没网等各种错误提示(把句号替换成空白)
//            MBProgressHUD .showNoNetwork(error.localizedDescription.replacingOccurrences(of: "。", with: ""))
        }
    }

Swift封装AFN网络请求

阅读数 36

废话不多说直接上代码importUIKitimportAFNetworking//swift的枚举支持任意类型//swift/enum在OC中只是支持整数enumWBHTTPMethod{caseGETcasePOST}/**-如果日常开发中,发现网络请求返回...

博文 来自: weixin_34138377

OC和Swift的AFN网络封装

阅读数 942

一、cocopos的使用创建项目之后,关闭项目,打开终端,cd空格,把项目所在的文件夹给拖进来,回车podinit然后把项目中生成的那个podfile项目拖到xcode,打开修改 pod'AFNetworking'cmt+S保存关闭在终端输入:podinstall--no-repo-update二、AF

博文 来自: wuxinzhitu

Swift处理AFN返回的json数据

阅读数 39

参考原文:http://swiftcafe.io/2015/07/18/swift-json/先抛开AFN不说,我们向服务器请求数据时,可以使用下面的方法:letaddr="http://api.budejie.com/api/api_open.php?a=list&c=data"leturl=U...

博文 来自: weixin_33713503

swift 开发中封装AFN

阅读数 23

今天呢讲讲开发中封装AFN封装吧因为AFN中AFHTTPResponseSerializer有个属性acceptableContentTypes这个呢就是你数据类型,我们需要把你的类型添加在这上面这样才能返回争取格式,那就上代码写个单例封装下吧屏幕快照2016-06-04下午1.49.36.png这个吧看我们使用吧...

博文 来自: weixin_33894640

swift - OC与swift3.0混编的项目中使用AFN

阅读数 10

//使用方法letparameters=["key1":1,"key2":2]WBNetwork.shareInstance.request(requestType:.GET,url:port1,params:parameters,success:{(responseObj)inprint(responseOb...

博文 来自: weixin_34194551
没有更多推荐了,返回首页