在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:SwiftHttp开源软件地址:https://gitee.com/knight2015/SwiftHttp开源软件介绍:Alamofire is an HTTP networking library written in Swift, from the creator of AFNetworking. Features
Requirements
Communication
InstallationDue to the current lack of proper infrastructure for Swift dependency management, using Alamofire in your project requires the following steps:
UsageMaking a Requestimport AlamofireAlamofire.request(.GET, "http://httpbin.org/get") Response HandlingAlamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .response { (request, response, data, error) in println(request) println(response) println(error) }
Response SerializationBuilt-in Response Methods
Response String HandlerAlamofire.request(.GET, "http://httpbin.org/get") .responseString { (_, _, string, _) in println(string) } Response JSON HandlerAlamofire.request(.GET, "http://httpbin.org/get") .responseJSON { (_, _, JSON, _) in println(JSON) } Chained Response HandlersResponse handlers can even be chained: Alamofire.request(.GET, "http://httpbin.org/get") .responseString { (_, _, string, _) in println(string) } .responseJSON { (_, _, JSON, _) in println(JSON) } HTTP Methods
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"} These values can be passed as the first argument of the Alamofire.request(.POST, "http://httpbin.org/post")Alamofire.request(.PUT, "http://httpbin.org/put")Alamofire.request(.DELETE, "http://httpbin.org/delete") ParametersGET Request With URL-Encoded ParametersAlamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])// http://httpbin.org/get?foo=bar POST Request With URL-Encoded Parameterslet parameters = [ "foo": "bar", "baz": ["a", 1], "qux": [ "x": 1, "y": 2, "z": 3 ]]Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters)// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3 Parameter EncodingParameters can also be encoded as JSON, Property List, or any custom format, using the enum ParameterEncoding { case URL case JSON case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions) func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) { ... }}
Manual Parameter Encoding of an NSURLRequestlet 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 Request with JSON-encoded Parameterslet parameters = [ "foo": [1,2,3], "bar": [ "baz": "qux" ]]Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON)// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}} CachingCaching is handled on the system framework level by UploadingSupported Upload Types
Uploading a Filelet fileURL = NSBundle.mainBundle() .URLForResource("Default", withExtension: "png")Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL) Uploading w/ProgressAlamofire.upload(.POST, "http://httpbin.org/post", file: fileURL) .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in println(totalBytesWritten) } .responseJSON { (request, response, JSON, error) in println(JSON) } DownloadingSupported Download Types
Downloading a FileAlamofire.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}) Using the Default Download Destinationlet destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination) Downloading a File w/ProgressAlamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination) .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in println(totalBytesRead) } .response { (request, response, _, error) in println(response) } AuthenticationAuthentication is handled on the system framework level by Supported Authentication Schemes HTTP Basic Authenticationlet user = "user"let password = "password"Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(user: user, password: password) .response {(request, response, _, error) in println(response) } Authentication with NSURLCredentiallet user = "user"let password = "password"let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(usingCredential: credential) .response {(request, response, _, error) in println(response) } ValidationBy default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling Manual ValidationAlamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .response { (_, _, _, error) in println(error) } Automatic ValidationAutomatically validates status code within Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .validate() .response { (_, _, _, error) in println(error) } Printablelet request = Alamofire.request(.GET, "http://httpbin.org/ip")println(request)// GET http://httpbin.org/ip (200) DebugPrintablelet 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" Advanced Usage
Recommended Reading
ManagerTop-level convenience methods like As such, the following two statements are equivalent: Alamofire.request(.GET, "http://httpbin.org/get") let manager = Alamofire.Manager.sharedInstancemanager.request(NSURLRequest(URL: NSURL(string: "http://httpbin.org/get"))) Applications can create managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers ( Creating a Manager with Default Configurationlet configuration = NSURLSessionConfiguration.defaultSessionConfiguration()let manager = Alamofire.Manager(configuration: configuration) Creating a Manager with Background Configurationlet configuration = NSURLSessionConfiguration.backgroundSessionConfiguration("com.example.app.background")let manager = Alamofire.Manager(configuration: configuration) Creating a Manager with Ephemeral Configurationlet configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()let manager = Alamofire.Manager(configuration: configuration) Modifying Session Configurationvar defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]defaultHeaders["DNT"] = "1 (Do Not Track Enabled)"let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()configuration.HTTPAdditionalHeaders = defaultHeaderslet manager = Alamofire.Manager(configuration: configuration)
RequestThe result of a Methods like Requests can be suspended, resumed, and cancelled:
Response SerializationCreating a Custom Response SerializerAlamofire provides built-in response serialization for strings, JSON, and property lists, but others can be added in extensions on For example, here's how a response handler using Ono might be implemented: extension Request { class func XMLResponseSerializer() -> Serializer { return { (request, response, data) in if data == nil { return (nil, nil) } var XMLSerializationError: NSError? let XML = ONOXMLDocument.XMLDocumentWithData(data, &XMLSerializationError) return (XML, XMLSerializationError) } } func responseXMLDocument(completionHandler: (NSURLRequest, NSHTTPURLResponse?, OnoXMLDocument?, NSError?) -> Void) -> Self { return response(serializer: Request.XMLResponseSerializer(), completionHandler: { (request, response, XML, error) in completionHandler(request, response, XML, error) }) }} Generic Response Object SerializationGenerics can be used to provide automatic, type-safe response object serialization. @objc public protocol ResponseObjectSerializable { init(response: NSHTTPURLResponse, representation: AnyObject)}extension Alamofire.Request { public func responseObject<T: ResponseObjectSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, T?, NSError?) -> Void) -> Self { let serializer: Serializer = { (request, response, data) in let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments) let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data) if response != nil && JSON != nil { return (T(response: response!, representation: JSON!), nil) } else { return (nil, serializationError) } }< |
请发表评论