NewsApp-master

所属分类:WEB开发
开发工具:Objective-C
文件大小:1627KB
下载次数:1
上传日期:2016-06-08 16:34:49
上 传 者abfeng112
说明:  模仿网易新闻,闲暇时写的,不太完善,见谅啊。
(Imitate netease news)

文件列表:
.DS_Store (6148, 2016-06-08)
__MACOSX (0, 2016-06-08)
._.DS_Store (120, 2016-06-08)
.podfile.swp (12288, 2016-03-10)
._.podfile.swp (222, 2016-03-10)
podfile (122, 2016-03-10)
._podfile (222, 2016-03-10)
Podfile.lock (425, 2016-03-10)
._Podfile.lock (222, 2016-03-10)
Pods (0, 2016-04-15)
Pods\Alamofire (0, 2016-04-15)
Pods\Alamofire\LICENSE (1104, 2016-03-10)
Pods (0, 2016-06-08)
Pods\Alamofire (0, 2016-06-08)
Pods\Alamofire\._LICENSE (222, 2016-03-10)
Pods\Alamofire\Source (0, 2016-04-15)
Pods\Alamofire\Source\Alamofire.swift (12475, 2016-03-10)
Pods\Alamofire\Source (0, 2016-06-08)
Pods\Alamofire\Source\._Alamofire.swift (222, 2016-03-10)
Pods\Alamofire\Source\Download.swift (10054, 2016-03-10)
Pods\Alamofire\Source\._Download.swift (222, 2016-03-10)
Pods\Alamofire\Source\Error.swift (3025, 2016-03-10)
Pods\Alamofire\Source\._Error.swift (222, 2016-03-10)
Pods\Alamofire\Source\Manager.swift (34538, 2016-03-10)
Pods\Alamofire\Source\._Manager.swift (222, 2016-03-10)
Pods\Alamofire\Source\MultipartFormData.swift (27031, 2016-03-10)
Pods\Alamofire\Source\._MultipartFormData.swift (222, 2016-03-10)
Pods\Alamofire\Source\ParameterEncoding.swift (11181, 2016-03-10)
Pods\Alamofire\Source\._ParameterEncoding.swift (222, 2016-03-10)
Pods\Alamofire\Source\Request.swift (19546, 2016-03-10)
Pods\Alamofire\Source\._Request.swift (222, 2016-03-10)
Pods\Alamofire\Source\Response.swift (3553, 2016-03-10)
Pods\Alamofire\Source\._Response.swift (222, 2016-03-10)
Pods\Alamofire\Source\ResponseSerialization.swift (13837, 2016-03-10)
Pods\Alamofire\Source\._ResponseSerialization.swift (222, 2016-03-10)
Pods\Alamofire\Source\Result.swift (3680, 2016-03-10)
... ...

![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/assets/alamofire.png) [![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg)](https://travis-ci.org/Alamofire/Alamofire) [![Cocoapods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) [![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) [![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](http://cocoadocs.org/docsets/Alamofire) [![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](http://twitter.com/AlamofireSF) Alamofire is an HTTP networking library written in Swift. ## Features - [x] Chainable Request / Response methods - [x] URL / JSON / plist Parameter Encoding - [x] Upload File / Data / Stream / MultipartFormData - [x] Download using Request or Resume data - [x] Authentication with NSURLCredential - [x] HTTP Response Validation - [x] TLS Certificate and Public Key Pinning - [x] Progress Closure & NSProgress - [x] cURL Debug Output - [x] Comprehensive Unit Test Coverage - [x] [Complete Documentation](http://cocoadocs.org/docsets/Alamofire) ## Requirements - iOS 8.0+ / Mac OS X 10.9+ / tvOS 9.0+ / watchOS 2.0+ - Xcode 7.1+ ## Migration Guides - [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) - [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) ## Communication - If you **need help**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). (Tag 'alamofire') - If you'd like to **ask a general question**, use [Stack Overflow](http://stackoverflow.com/questions/tagged/alamofire). - If you **found a bug**, open an issue. - If you **have a feature request**, open an issue. - If you **want to contribute**, submit a pull request. ## Installation > **Embedded frameworks require a minimum deployment target of iOS 8 or OS X Mavericks (10.9).** > > Alamofire is no longer supported on iOS 7 due to the lack of support for frameworks. Without frameworks, running Travis-CI against iOS 7 would require a second duplicated test target. The separate test suite would need to import all the Swift files and the tests would need to be duplicated and re-written. This split would be too difficult to maintain to ensure the highest possible quality of the Alamofire ecosystem. ### CocoaPods [CocoaPods](http://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: ```bash $ gem install cocoapods ``` > CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! pod 'Alamofire', '~> 3.0' ``` Then, run the following command: ```bash $ pod install ``` ### Carthage [Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. You can install Carthage with [Homebrew](http://brew.sh/) using the following command: ```bash $ brew update $ brew install carthage ``` To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: ```ogdl github "Alamofire/Alamofire" ~> 3.0 ``` Run `carthage` to build the framework and drag the built `Alamofire.framework` into your Xcode project. ### Manually If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually. #### Embedded Framework - Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: ```bash $ git init ``` - Add Alamofire as a git [submodule](http://git-scm.com/docs/git-submodule) by running the following command: ```bash $ git submodule add https://github.com/Alamofire/Alamofire.git ``` - Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. - Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. - In the tab bar at the top of that window, open the "General" panel. - Click on the `+` button under the "Embedded Binaries" section. - You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - Select the top `Alamofire.framework` for iOS and the bottom one for OS X. > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS` or `Alamofire OSX`. - And that's it! > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. --- ## Usage ### Making a Request ```swift import Alamofire Alamofire.request(.GET, "http://httpbin.org/get") ``` ### Response Handling ```swift Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .responseJSON { response in print(response.request) // original URL request print(response.response) // URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } ``` > Networking in Alamofire is done _asynchronously_. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are [very good reasons](https://developer.apple.com/library/ios/qa/qa1693/_index.html) for doing it this way. > Rather than blocking execution to wait for a response from the server, a [callback](http://en.wikipedia.org/wiki/Callback_%28computer_programming%29) is specified to handle the response once it's received. The result of a request is only available inside the scope of a response handler. Any execution contingent on the response or data received from the server must be done within a handler. ### Response Serialization **Built-in Response Methods** - `response()` - `responseData()` - `responseString(encoding: NSStringEncoding)` - `responseJSON(options: NSJSONReadingOptions)` - `responsePropertyList(options: NSPropertyListReadOptions)` #### Response Handler ```swift Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .response { request, response, data, error in print(request) print(response) print(data) print(error) } ``` > The `response` serializer does NOT evaluate any of the response data. It merely forwards on all the information directly from the URL session delegate. We strongly encourage you to leverage the other responser serializers taking advantage of `Response` and `Result` types. #### Response Data Handler ```swift Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .responseData { response in print(response.request) print(response.response) print(response.result) } ``` #### Response String Handler ```swift Alamofire.request(.GET, "http://httpbin.org/get") .responseString { response in print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)") } ``` #### Response JSON Handler ```swift Alamofire.request(.GET, "http://httpbin.org/get") .responseJSON { response in debugPrint(response) } ``` #### Chained Response Handlers Response handlers can even be chained: ```swift Alamofire.request(.GET, "http://httpbin.org/get") .responseString { response in print("Response String: \(response.result.value)") } .responseJSON { response in print("Response JSON: \(response.result.value)") } ``` ### HTTP Methods `Alamofire.Method` lists the HTTP methods defined in [RFC 7231 4.3](http://tools.ietf.org/html/rfc7231#section-4.3): ```swift public enum Method: String { case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT } ``` These values can be passed as the first argument of the `Alamofire.request` method: ```swift Alamofire.request(.POST, "http://httpbin.org/post") Alamofire.request(.PUT, "http://httpbin.org/put") Alamofire.request(.DELETE, "http://httpbin.org/delete") ``` ### Parameters #### GET Request With URL-Encoded Parameters ```swift Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) // http://httpbin.org/get?foo=bar ``` #### POST Request With URL-Encoded Parameters ```swift let 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 Encoding Parameters can also be encoded as JSON, Property List, or any custom format, using the `ParameterEncoding` enum: ```swift enum ParameterEncoding { case URL case URLEncodedInURL case JSON case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions) case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) { ... } } ``` - `URL`: A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. _Since there is no published specification for how to encode collection types, Alamofire follows the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`)._ - `URLEncodedInURL`: Creates query string to be set as or appended to any existing URL query. Uses the same implementation as the `.URL` case, but always applies the encoded result to the URL. - `JSON`: Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. - `PropertyList`: Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`. - `Custom`: Uses the associated closure value to construct a new request given an existing request and parameters. #### Manual Parameter Encoding of an NSURLRequest ```swift let URL = NSURL(string: "http://httpbin.org/get")! var request = NSMutableURLRequest(URL: URL) let parameters = ["foo": "bar"] let encoding = Alamofire.ParameterEncoding.URL (request, _) = encoding.encode(request, parameters: parameters) ``` #### POST Request with JSON-encoded Parameters ```swift let 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"}} ``` ### HTTP Headers Adding a custom HTTP header to a `Request` is supported directly in the global `request` method. This makes it easy to attach HTTP headers to a `Request` that can be constantly changing. > For HTTP headers that do not change, it is recommended to set them on the `NSURLSessionConfiguration` so they are automatically applied to any `NSURLSessionTask` created by the underlying `NSURLSession`. ```swift let headers = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", "Content-Type": "application/x-www-form-urlencoded" ] Alamofire.request(.GET, "http://httpbin.org/get", headers: headers) .responseJSON { response in debugPrint(response) } ``` ### Caching Caching is handled on the system framework level by [`NSURLCache`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLCache_Class/Reference/Reference.html#//apple_ref/occ/cl/NSURLCache). ### Uploading **Supported Upload Types** - File - Data - Stream - MultipartFormData #### Uploading a File ```swift let fileURL = NSBundle.mainBundle().URLForResource("Default", withExtension: "png") Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL) ``` #### Uploading with Progress ```swift Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL) .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in print(totalBytesWritten) // This closure is NOT called on the main queue for performance // reasons. To update your ui, dispatch to the main queue. dispatch_async(dispatch_get_main_queue()) { print("Total bytes written on main queue: \(totalBytesWritten)") } } .responseJSON { response in debugPrint(response) } ``` #### Uploading MultipartFormData ```swift Alamofire.upload( .POST, "http://httpbin.org/post", multipartFormData: { multipartFormData in multipartFormData.appendBodyPart(fileURL: unicornImageURL, name: "unicorn") multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name: "rainbow") }, encodingCompletion: { encodingResult in switch encodingResult { case .Success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .Failure(let encodingError): print(encodingError) } } ) ``` ### Downloading **Supported Download Types** - Request - Resume Data #### Downloading a File ```swift Alamofire.download(.GET, "http://httpbin.org/stream/100") { temporaryURL, response in let fileManager = NSFileManager.defaultManager() let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] let pathComponent = response.suggestedFilename return directoryURL.URLByAppendingPathComponent(pathComponent!) } ``` #### Using the Default Download Destination ```swift let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination) ``` #### Downloading a File w/Progress ```swift Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination) .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in print(totalBytesRead) // This closure is NOT called on the main queue for performance // reasons. To update your ui, dispatch to the main queue. dispatch_async(dispatch_get_main_queue()) { print("Total bytes read on main queue: \(totalBytesRead)") } } .response { _, _, _, error in if let error = error { print("Failed with error: \(error)") } else { print("Downloaded file successfully") } } ``` #### Accessing Resume Data for Failed Downloads ```swift Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination) .response { _, _, data, _ in if let data = data, resumeDataString = NSString(data: data, encoding: NSUTF8StringEncoding) { print("Resume Data: \(resumeDataString)") } else { print("Resume Data was empty") } } ``` > The `data` parameter is automatically populated with the `resumeData` if available. ```swift let download = Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination) download.response { _, _, _, _ in if let resumeData = download.resumeData, resumeDataString = NSString(data: resumeData, encoding: NSUTF8StringEncoding) { print("Resume Data: \(resumeDataString)") } else { print("Resume Data was empty") } } ``` ### Authentication Authentication is handled on the system framework level by [`NSURLCredential` and `NSURLAuthenticationChallenge`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLAuthenticationChallenge_Class/Reference/Reference.html). **Supported Authentication Schemes** - [HTTP Basic](http://en.wikipedia.org/wiki/Basic_access_authentication) - [HTTP Digest](http://en.wikipedia.org/wiki/Digest_access_authentication) - [Kerberos](http://en.wikipedia.org/wiki/Kerberos_%28protocol%29) - [NTLM](http://en.wikipedia.org/wiki/NT_LAN_Manager) #### HTTP Basic Authentication The `authenticate` method on a `Request` will automatically provide an `NSURLCredential` to an `NSURLAuthenticationChallenge` when appropriate: ```swift let user = "user" let password = "password" Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(user: user, password: password) .responseJSON { response in debugPrint(response) } ``` Depending upon your server implementation, an `Authorization` header may also be appropriate: ```swift let user = "user" let password = "password" let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)! let base***Credentials = credentialData.base***EncodedStringWithOptions([]) let headers = ["Authorization": "Basic \(base***Credentials)"] Alamofire.request(.GET, "http://httpbin.org/basic-auth/user/password", headers: headers) .responseJSON { response in debugPrint(response) } ``` #### Authentication with NSURLCredential ```swift let 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 ... ...

近期下载者

相关文件


收藏者