魏名华

不要偷懒,做更好的自己

Nothing


No Welcome Message

Apikit笔记 20161205

APIKit笔记-20161205

  1. 最新文档注释
  2. Request

最新文档注释

Add Documentation alt+command+/


Build

从github clone 项目后,并不能直接编译,找不到Result项目,需要先用命令行执行swift build,Package.swift文件中有build依赖等配置,之后可以使用xcode build或test


Request

protocol Request定义了请求的各要素,Response,dataParser,以及intercept

Intercepts URLRequest

buildURLRequest()会构建URLRequest,构建的最后一步会调用intercept方法,以修改URLRequest

Intercepts response

extension Request

提供协议的默认实现,另外提供了buildURLRequest(), parse(…)方法


URLEncodedSerialization

parameters: ["q": "こんにちは"] // 0--

let pairs = dictionary.map { key, value -> String in
    if value is NSNull {
        return "\(escape(key))" // private func escape(_ string: String) -> String
    }

    let valueAsString = (value as? String) ?? "\(value)"
    return "\(escape(key))=\(escape(valueAsString))"
} // 1--[0 : "q=%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF"]

pairs.joined(separator: "&") // 2--"q=%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF"

parameters: ["null": NSNull()] // 0--
// 1--[0 : "null"]
// 2--"null"

forEach

headerFields.forEach { key, value in
    urlRequest.setValue(value, forHTTPHeaderField: key)
}

flatMap

该函数会将那些多维集合类型转换为一维集合类型

let json = urlRequest?.httpBody.flatMap { try? JSONSerialization.jsonObject(with: $0, options: []) } as? [AnyObject]

等价于    

let json = urlRequest?.httpBody.map { try? JSONSerialization.jsonObject(with: $0, options: []) } as? [AnyObject]

等价于

var json: [AnyObject]?;
if let body = urlRequest?.httpBody {
    json = try? JSONSerialization.jsonObject(with: body, options: []) as! [AnyObject]
}

JSONBodyParameters

enum在swift中的运用

public enum RequestBodyEntity {
    case data(Data)
    case inputStream(InputStream)
}

public protocol BodyParameters {
    var contentType: String { get }
    func buildEntity() throws -> RequestBodyEntity
}

public struct JSONBodyParameters: BodyParameters {
    public func buildEntity() throws -> RequestBodyEntity {
        guard JSONSerialization.isValidJSONObject(JSONObject) else {
            throw NSError(domain: NSCocoaErrorDomain, code: 3840, userInfo: nil)
        }

        return .data(try JSONSerialization.data(withJSONObject: JSONObject, options: writingOptions))
    }

    ...
}

switch try bodyParameters.buildEntity() {
    case .data(let data):
        urlRequest.httpBody = data

    case .inputStream(let inputStream):
        urlRequest.httpBodyStream = inputStream
}

XCTestCase

let expectation = self.expectation(description: "wait for response")
let request = TestRequest()

session.send(request, callbackQueue: .main) { result in
    XCTAssert(Thread.isMainThread)
    expectation.fulfill()
}

waitForExpectations(timeout: 1.0, handler: nil) // Runs the run loop while handling events until all expectations are fulfilled or the timeout is reached.

Session

ModuleA->Session: send
Session->SessionAdapter: createTask
Session->Session: setRequest // 将request动态绑定到task
Session->SessionTask: task.resume()
SessionTask-->>Session: 异步返回data
Session-->ModuleA: 同步返回Result

??

let callbackQueue = callbackQueue ?? self.callbackQueue


open

ModuleA.framework

public class PublicClass // 这个类在ModuleA的范围外是不能被继承的,只能被访问 open class OpenClass // 在ModuleA的范围外可以被继承