swiftui网络请求框架 swift 网络框架

admin2024-05-30  14

框架概述

swift 版的 AFNetworking,提供了便利的在 swift 语言网络访问的框架。可以很容易的发起网络请求

Alamofire结构

swiftui网络请求框架 swift 网络框架,swiftui网络请求框架 swift 网络框架_swiftui网络请求框架,第1张

  • Alamofire.swift 主要是一些公用协议的声明和对外开放调用接口。主要使用此文件下的方法进行网络请求,里面封装了 网络请求、上传、下载等方法。还有一些扩展的。
  • Download.swift封装了关于下载的各种方法。
  • Manager.swfit是一个单列类,组装了访问的核心功能,Alamofire.swift也是调用此文件提供的方法。
  • ParameterEncoding.swift定义了参数的编码方式。
  • Request.swift拼装了 NSHttpRequest 请求。
  • UPload.swift定义了上传操作接口。
  • Validation.swift与权限有关
  • ResponseSerialization.swift回调相关的反序列化操作。

使用方法在后面

swift 的扩展特性是我们使用 Alamofire 更加的方便,在得到网络请求后,可以进行进一步对数据的操作。更贴切面向对象的思想,比较方便的就是对 Request 进行扩展,拿到不一样的数据后可以进行相应的处理后在返回。

进行扩展

如下代码分别对返回的数据做出了不同处理

//对返回的数据为集合类进行处理
extension Alamofire.Request{
    public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, [T]?, NSError?) -> Void) ->Self{

        let responseSerializer = GenericResponseSerializer<[T]> {request,response,data in
            let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON:AnyObject?,serializationError) = JSONResponseSerializer.serializeResponse(request,response,data)

            if let response = response,JSON:AnyObject = JSON {

                return (T.collection(response: response, representation: JSON), nil)

            }else{
                return(nil,serializationError)
            }
        }
        return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
    }
}

@objc public protocol ResponseObjectSerializable{
    init?(response:NSHTTPURLResponse, representation:AnyObject)
}

//对 JSON 数据进行处理
extension Alamofire.Request{
    public func responseObject<T:ResponseObjectSerializable>(completionHandler:(NSURLRequest,NSHTTPURLResponse?,T?,NSError?) ->Void ) ->Self {
        let responseSerializer = GenericResponseSerializer<T>{request,response,data in
            let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
            let (JSON:AnyObject?,serializerError) = JSONResponseSerializer.serializeResponse(request,response,data)

            if let response = response, JSON:AnyObject = JSON{
                return (T(response: response, representation: JSON),nil)
            }else{
                return(nil,serializerError)
            }
        }
        return response(responseSerializer:responseSerializer,completionHandler:completionHandler)
    }
}

//对返回的图片数据进行处理
extension Alamofire.Request {
    public static func imageResponseSerializer() -> GenericResponseSerializer<UIImage> {
        return GenericResponseSerializer { request, response, data in
            if data == nil {
                return (nil, nil)
            }

            let image = UIImage(data: data!, scale: UIScreen.mainScreen().scale)

            return (image, nil)
        }
    }

    public func responseImage(completionHandler: (NSURLRequest, NSHTTPURLResponse?, UIImage?, NSError?) -> Void) -> Self {
        return response(responseSerializer: Request.imageResponseSerializer(), completionHandler: completionHandler)
    }
}

扩展后的使用

Alamofire.request(.GET, photoInfo!.url).validate().responseImage() {
                    (_, _, image, error) in

                    if error == nil && image != nil {
                        self.imageView.image = image
                        self.imageView.frame = self.centerFrameFromImage(image)

                        self.spinner.stopAnimating()

                        self.centerScrollViewContents()
                    }
                }

使用方法

以下内容为摘取 github 上给出的文档实例。

GET 请求

Alamofire.request(.GET, "http://httpbin.org/get")

带参数

Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
Response结果处理
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .response { (request, response, data, error) in
                     println(request)
                     println(response)
                     println(error)
                   }
Response结果字符串处理
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
         .responseString { (request, response, string, error) in
                  println(string)
         }

HTTP 方法(Medthods)

Alamofire.Method enum 列表出在RFC 2616中定义的HTTP方法 §9:

public enum Method: String {
    case OPTIONS = "OPTIONS"
    case GET = "GET"
    case HEAD = "HEAD"
    case POST = "POST"
    case PUT = "PUT"
    case PATCH = "PATCH"
    case DELETE = "DELETE"
    case TRACE = "TRACE"
    case CONNECT = "CONNECT"
}

这些值可以作为Alamofire.request请求的第一个参数.

Alamofire.request(.POST, "http://httpbin.org/post")

Alamofire.request(.PUT, "http://httpbin.org/put")

Alamofire.request(.DELETE, "http://httpbin.org/delete")

POST请求

let parameters = [
    "foo": "bar",
    "baz": ["a", 1],
    "qux": [
        "x": 1,
        "y": 2,
        "z": 3
    ]
]

Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters)

发送以下HttpBody内容:

foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
Alamofire 使用Alamofire.ParameterEncoding可以支持URL query/URI form,JSON, PropertyList方式编码参数。

Parameter Encoding

enum ParameterEncoding {
    case URL
    case JSON(options: NSJSONWritingOptions)
    case PropertyList(format: NSPropertyListFormat,
                      options: NSPropertyListWriteOptions)

    func encode(request: NSURLRequest,
                parameters: [String: AnyObject]?) ->
                    (NSURLRequest, NSError?)
    { ... }
}

NSURLRequest方式编码参数

let URL = NSURL(string: "http://httpbin.org/get")
var request = NSURLRequest(URL: URL)

let parameters = ["foo": "bar"]
let encoding = Alamofire.ParameterEncoding.URL
(request, _) = encoding.encode(request, parameters)
POST JSON格式数据
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON(options: nil))
         .responseJSON {(request, response, JSON, error) in
            println(JSON)
         }

Response 方法

response()
responseString(encoding: NSStringEncoding)
responseJSON(options: NSJSONReadingOptions)
responsePropertyList(options: NSPropertyListReadOptions)

上传(Uploading)

支持的类型

File
Data
Stream
Multipart (Coming Soon)

上传文件

let fileURL = NSBundle.mainBundle()
                      .URLForResource("Default",
                                      withExtension: "png")

Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)

上传进度

Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
        .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
            println(totalBytesWritten)
        }
        .responseJSON { (request, response, JSON, error) in
            println(JSON)
        }

下载

支持的类型

Request
Resume Data

下载文件

Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: { (temporaryURL, response) in
    if let directoryURL = NSFileManager.defaultManager()
                          .URLsForDirectory(.DocumentDirectory,
                                            inDomains: .UserDomainMask)[0]
                          as? NSURL {
        let pathComponent = response.suggestedFilename

        return directoryURL.URLByAppendingPathComponent(pathComponent)
    }

    return temporaryURL
})

下载到默认路径

let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)

Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)

下载进度

Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
         .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
             println(totalBytesRead)
         }
         .response { (request, response, _, error) in
             println(response)
         }

认证(Authentication)

支持以下几种认证

HTTP Basic
HTTP Digest
Kerberos
NTLM

Http basic认证

let user = "user"
let password = "password"

Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
    .authenticate(HTTPBasic: user, password: password)
    .response {(request, response, _, error) in
        println(response)
        }

采用NSURLCredential&NSURLProtectionSpace方式认证

let user = "user"
let password = "password"

let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
let protectionSpace = NSURLProtectionSpace(host: "httpbin.org", port: 0, `protocol`: "https", realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
    .authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
    .response {(request, response, _, error) in
        println(response)
}

调试

let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])

debugPrintln(request)
Output (cURL)

$ curl -i \
    -H "User-Agent: Alamofire" \
    -H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" \
    -H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \
    "http://httpbin.org/get?foo=bar"


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!