Giter Site home page Giter Site logo

alamofire / alamofire Goto Github PK

View Code? Open in Web Editor NEW
40.5K 1.1K 7.5K 34.84 MB

Elegant HTTP Networking in Swift

License: MIT License

Swift 99.94% Ruby 0.06%
networking urlsession urlrequest httpurlresponse request response swift xcode certificate-pinning public-key-pinning

alamofire's Introduction

Alamofire: Elegant Networking in Swift

Swift Platforms CocoaPods Compatible Carthage Compatible Swift Package Manager Swift Forums

Alamofire is an HTTP networking library written in Swift.

Features

  • Chainable Request / Response Methods
  • Swift Concurrency Support Back to iOS 13, macOS 10.15, tvOS 13, and watchOS 6.
  • Combine Support
  • URL / JSON Parameter Encoding
  • Upload File / Data / Stream / MultipartFormData
  • Download File using Request or Resume Data
  • Authentication with URLCredential
  • HTTP Response Validation
  • Upload and Download Progress Closures with Progress
  • cURL Command Output
  • Dynamically Adapt and Retry Requests
  • TLS Certificate and Public Key Pinning
  • Network Reachability
  • Comprehensive Unit and Integration Test Coverage
  • Complete Documentation

Write Requests Fast!

Alamofire's compact syntax and extensive feature set allow requests with powerful features like automatic retry to be written in just a few lines of code.

// Automatic String to URL conversion, Swift concurrency support, and automatic retry.
let response = await AF.request("https://httpbin.org/get", interceptor: .retryPolicy)
                       // Automatic HTTP Basic Auth.
                       .authenticate(username: "user", password: "pass")
                       // Caching customization.
                       .cacheResponse(using: .cache)
                       // Redirect customization.
                       .redirect(using: .follow)
                       // Validate response code and Content-Type.
                       .validate()
                       // Produce a cURL command for the request.
                       .cURLDescription { description in
                         print(description)
                       }
                       // Automatic Decodable support with background parsing.
                       .serializingDecodable(DecodableType.self)
                       // Await the full response with metrics and a parsed body.
                       .response
// Detailed response description for easy debugging.
debugPrint(response)

Component Libraries

In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the Alamofire Software Foundation to bring additional functionality to the Alamofire ecosystem.

  • AlamofireImage - An image library including image response serializers, UIImage and UIImageView extensions, custom image filters, an auto-purging in-memory cache, and a priority-based image downloading system.
  • AlamofireNetworkActivityIndicator - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support URLSession instances not managed by Alamofire.

Requirements

Platform Minimum Swift Version Installation Status
iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ 5.7.1 / Xcode 14.1 CocoaPods, Carthage, Swift Package Manager, Manual Fully Tested
Linux Latest Only Swift Package Manager Building But Unsupported
Windows Latest Only Swift Package Manager Building But Unsupported
Android Latest Only Swift Package Manager Building But Unsupported

Known Issues on Linux and Windows

Alamofire builds on Linux, Windows, and Android but there are missing features and many issues in the underlying swift-corelibs-foundation that prevent full functionality and may cause crashes. These include:

  • ServerTrustManager and associated certificate functionality is unavailable, so there is no certificate pinning and no client certificate support.
  • Various methods of HTTP authentication may crash, including HTTP Basic and HTTP Digest. Crashes may occur if responses contain server challenges.
  • Cache control through CachedResponseHandler and associated APIs is unavailable, as the underlying delegate methods aren't called.
  • URLSessionTaskMetrics are never gathered.
  • WebSocketRequest is not available.

Due to these issues, Alamofire is unsupported on Linux, Windows, and Android. Please report any crashes to the Swift bug reporter.

Migration Guides

Communication

Installation

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the swift compiler.

Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the dependencies value of your Package.swift or the Package list in Xcode.

dependencies: [
    .package(url: "https://github.com/Alamofire/Alamofire.git", .upToNextMajor(from: "5.9.1"))
]

Normally you'll want to depend on the Alamofire target:

.product(name: "Alamofire", package: "Alamofire")

But if you want to force Alamofire to be dynamically linked (do not do this unless you're sure you need it), you can depend on the AlamofireDynamic target:

.product(name: "AlamofireDynamic", package: "Alamofire")

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate Alamofire into your Xcode project using CocoaPods, specify it in your Podfile:

pod 'Alamofire'

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate Alamofire into your Xcode project using Carthage, specify it in your Cartfile:

github "Alamofire/Alamofire"

Manually

If you prefer not to use any 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:

    $ git init
  • Add Alamofire as a git submodule by running the following command:

    $ 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 macOS.

    You can verify which one you selected by inspecting the build log for your project. The build target for Alamofire will be listed as Alamofire iOS, Alamofire macOS, Alamofire tvOS, or Alamofire watchOS.

  • 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.

Contributing

Before contributing to Alamofire, please read the instructions detailed in our contribution guide.

Open Radars

The following radars have some effect on the current implementation of Alamofire.

  • rdar://21349340 - Compiler throwing warning due to toll-free bridging issue in the test case
  • rdar://26870455 - Background URL Session Configurations do not work in the simulator
  • rdar://26849668 - Some URLProtocol APIs do not properly handle URLRequest

Resolved Radars

The following radars have been resolved over time after being filed against the Alamofire project.

  • rdar://26761490 - Swift string interpolation causing memory leak with common usage.
    • (Resolved): 9/1/17 in Xcode 9 beta 6.
  • rdar://36082113 - URLSessionTaskMetrics failing to link on watchOS 3.0+
    • (Resolved): Just add CFNetwork to your linked frameworks.
  • FB7624529 - urlSession(_:task:didFinishCollecting:) never called on watchOS
    • (Resolved): Metrics now collected on watchOS 7+.

FAQ

What's the origin of the name Alamofire?

Alamofire is named after the Alamo Fire flower, a hybrid variant of the Bluebonnet, the official state flower of Texas.

Credits

Alamofire is owned and maintained by the Alamofire Software Foundation. You can follow them on Twitter at @AlamofireSF for project updates and releases.

Security Disclosure

If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to [email protected]. Please do not post it to a public issue tracker.

Sponsorship

The ASF is looking to raise money to officially stay registered as a federal non-profit organization. Registering will allow Foundation members to gain some legal protections and also allow us to put donations to use, tax-free. Sponsoring the ASF will enable us to:

  • Pay our yearly legal fees to keep the non-profit in good status
  • Pay for our mail servers to help us stay on top of all questions and security issues
  • Potentially fund test servers to make it easier for us to test the edge cases
  • Potentially fund developers to work on one of our projects full-time

The community adoption of the ASF libraries has been amazing. We are greatly humbled by your enthusiasm around the projects and want to continue to do everything we can to move the needle forward. With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. If you use any of our libraries for work, see if your employers would be interested in donating. Any amount you can donate, whether once or monthly, to help us reach our goal would be greatly appreciated.

Sponsor Alamofire

Supporters

MacStadium provides Alamofire with a free, hosted Mac mini.

Powered by MacStadium

License

Alamofire is released under the MIT license. See LICENSE for details.

alamofire's People

Contributors

0xced avatar antrix1989 avatar ashton-w avatar cnoon avatar dependabot[bot] avatar dirtmelon avatar fulldecent avatar getaaron avatar hugo-syn avatar ikesyo avatar ishkawa avatar johngibb avatar joshuatbrown avatar jshier avatar kcharwood avatar kth1210 avatar kylef avatar lucatorella avatar lutzifer avatar mattt avatar mk avatar passchaos avatar philtre avatar rain2540 avatar rastersize avatar teameh avatar tiagomaial avatar vishrutshah avatar watarusuzuki avatar yasuoza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alamofire's Issues

Basic Auth user credentials not being passed with request

I'm trying to use the example from NSHipster to do Basic Auth. I form my request like so:

        Alamofire.request(.POST, "https://my.url.com/api/v1/auth")
            .authenticate(HTTPBasic: email, password: password)
            .responseJSON {(request, response, JSON, error) in
                println(request)
                println(response)
                println(JSON)
                println(error)
        }

Email and password are just strings here. I am getting a response suggesting that the credentials aren't attached.

Optional(<NSHTTPURLResponse: 0x7fb699783080> { URL: https://my.url.com/api/v1/auth } { status code: 401, headers {
    Allow = "POST, OPTIONS";
    Connection = "keep-alive";
    "Content-Language" = "en-us";
    "Content-Length" = 59;
    "Content-Type" = "application/json";
    Date = "Mon, 11 Aug 2014 13:34:36 GMT";
    Server = "gunicorn/17.5";
    Vary = "Accept, Accept-Language";
    "Www-Authenticate" = "Basic realm=\"api\"";
    "X-Frame-Options" = SAMEORIGIN;
} })
Optional({
    detail = "Authentication credentials were not provided.";
})

When I make the same request while using AFNetworking, I get a successful 200 response.

        let manager = AFHTTPRequestOperationManager()
        manager.requestSerializer.clearAuthorizationHeader()
        manager.requestSerializer.setAuthorizationHeaderFieldWithUsername(emailTextField.text, password:passwordTextField.text)
        manager.POST(
            "https://my.url.com/api/v1/auth",
            parameters: nil,
            success: { (operation: AFHTTPRequestOperation!,
                responseObject: AnyObject!) in
                println("JSON: " + responseObject.description)
            },
            failure: { (operation: AFHTTPRequestOperation!,
                error: NSError!) in
                println("Error: " + error.localizedDescription)
        })

If I'm making a mistake in my request with AlamoFire, would you mind pointing it out?

Errors when building with Xcode6-beta6

Building fails with the following errors.

Alamofire.swift:60:47: Cannot reference a local function from another local function
Alamofire.swift:69:47: Cannot reference a local function from another local function
Alamofire.swift:107:41: Optional type '()' cannot be used as a boolean; test for '!= nil' instead
Alamofire.swift:107:80: Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
Alamofire.swift:110:40: Optional type 'String!' cannot be used as a boolean; test for '!= nil' instead
Alamofire.swift:118:67: Value of optional type '[String : AnyObject]?' not unwrapped; did you mean to use '!' or '?'?
Alamofire.swift:126:77: Value of optional type '[String : AnyObject]?' not unwrapped; did you mean to use '!' or '?'?
Alamofire.swift:176:53: Bound value in a conditional binding must be of Optional type
Alamofire.swift:180:68: Operand of postfix '?' should have optional type; type is 'NSProcessInfo'
Alamofire.swift:212:36: Optional type 'String!' cannot be used as a boolean; test for '!= nil' instead
Alamofire.swift:681:21: Optional type '@lvalue ((Int64, Int64, Int64) -> Void)!' cannot be used as a boolean; test for '!= nil' instead
Alamofire.swift:795:17: Optional type '$T1' cannot be used as a boolean; test for '!= nil' instead
Alamofire.swift:814:35: Optional type 'NSURLProtectionSpace' cannot be used as a boolean; test for '!= nil' instead
Alamofire.swift:865:41: Value of optional type 'NSData?' not unwrapped; did you mean to use '!' or '?'?
Alamofire.swift:887:75: Value of optional type 'NSData?' not unwrapped; did you mean to use '!' or '?'?
Alamofire.swift:909:86: Value of optional type 'NSData?' not unwrapped; did you mean to use '!' or '?'?
Alamofire.swift:42:18: Cannot create a single-element tuple with an element label

How do I add a value to an http header?

I am interested in adding an additional value to the following GET request's header:

let galleryRequest = Alamofire.request(.GET, "https://api.imgur.com/3/gallery.json")
    .responseString { (request, response, string, error) in
         // Do something...
    }

The header in question is: Authorization: Client-ID YOUR_CLIENT_ID where the client_id would be my imgur client_id.

Thanks for the awesome library!

fatal error: unexpectedly found nil while unwrapping an Optional value

Everytime I use the sample code supplied on http://nshipster.com/alamofire/, this error comes up.
This is the code that is given:

Alamofire.request(.GET, "http://httpbin.org/get")
    .response { (request, response, data, error) in
        println(request)
        println(response)
        println(error)
}

and here is the piece of code that is erroring (line 182):

var mutableUserAgent = NSMutableString(string: "\(executable!)/\(bundle!) (\(version!); OS \(os!))") as CFMutableString

No such module 'Alamofire' when used for Mac OS Cocoa application

Environment

Mac OS X 10.9.4
Xcode 6 beta 7
Alamofire @ commit 72206e5

Steps to reproduce

  1. Create new Mac OS X project, simple Cocoa application
    • language: Swift
    • use storyboards: NO
    • document based: NO
    • core data: NO
  2. Drag the Alamofire.xcodeproj into your new project (as instructed in the README file)
  3. From the 'build phase' tab, add a target dependency, select Alamofire's framework
  4. Open AppDelegate.swift, under import Cocoa add import Alamofire
  5. Build and run
  6. ../AlamofireDemo/AppDelegate.swift:10:8: No such module 'Alamofire'

iOS 7 bug

I encountered a bug where the response is always empty on iOS 7. I don't really know what's going on but I thin I tracked it down to this method:

func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
  if let delegate = self[dataTask] as? Request.DataTaskDelegate {
    delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) // never reached on iOS 7
  }

  self.dataTaskDidReceiveData?(session, dataTask, data)
}

On iOS 8 it enters the if block, on iOS 7 it doesn't.

I really don't know much about that stuff - I hope that's useful information and someone who understands this better than me can fix it ;)

Invalid JSON in POST request

This is the request format required for a particulat API call.

{
  "UserCredentials": {
    "Personalnumber": "sample string 1",
    "Password": "sample string 2"
  },
  "DeviceCredentials": {
    "UniqueId": "sample string 1"
  }
}

I created the parameters constant like this,

let parameters = [
    "UserCredentials": [
        "Personalnumber": personalNumber,
        "Password": password
    ],
    "DeviceCredentials": ["UniqueId": uniqueID]
]

No compile errors. I sent this via a POST request. But it failed with the following error.
The operation couldn’t be completed. (Cocoa error 3840.)

I prinln-ed out the 3 values I set (personalNumber, password, uniqueID) to see if I'm passing a nil somewhere but all the values are set properly.

Then I dived in to the Alamofire class and put a println inside the ParameterEncoding enum's .JSON case. This is the output I got.

[UserCredentials: {
    Password = 123456;
    Personalnumber = 191212121212;
}, DeviceCredentials: {
    UniqueId = 70788AEB8586513C46B0599AEA4F82BF;
}]

Apart from this I'm out of ideas on how to track down the error. Any suggestions? Any idea as to what might be causing this?

Linker error in XCode6-beta6

When I add Alamofire in my project I get the following Linker error:
Undefined symbols for architecture i386:
"TFSs15_arrayForceCastU___FGSaQ__GSaQ0", referenced from:
TFFFC9Alamofire7Managerg14defaultHeadersGVSs10DictionarySSSS_U_FT_GS1_SSSS_U_FT_SS in Alamofire.o
"_TFSs21_arrayConditionalCastU___FGSaQ__GSqGSaQ0
", referenced from:
__TFC9Alamofire7Request18cURLRepresentationfS0_FT_SS in Alamofire.o
"_TFSs26_forceBridgeFromObjectiveCU__FTPSs9AnyObject_MQ__Q", referenced from:
_TFC9Alamofire7Request12authenticatefDS0_FT9HTTPBasicSS8passwordSS_DS0 in Alamofire.o
_TFCC9Alamofire7Request12TaskDelegate10URLSessionfS1_FTGSQCSo12NSURLSession_4taskGSQCSo16NSURLSessionTask_19didReceiveChallengeGSQCSo28NSURLAuthenticationChallenge_17completionHandlerGSQFTOSC36NSURLSessionAuthChallengeDispositionGSQCSo15NSURLCredential__T___T in Alamofire.o
__TFC9Alamofire7Request18cURLRepresentationfS0_FT_SS in Alamofire.o
__TFFFC9Alamofire7Managerg14defaultHeadersGVSs10DictionarySSSS_U_FT_GS1_SSSS_U0_FT_SS in Alamofire.o
"_swift_stdlib_compareNSStringDeterministicUnicodeCollation", referenced from:
_TFCC9Alamofire7Request12TaskDelegate10URLSessionfS1_FTGSQCSo12NSURLSession_4taskGSQCSo16NSURLSessionTask_19didReceiveChallengeGSQCSo28NSURLAuthenticationChallenge_17completionHandlerGSQFTOSC36NSURLSessionAuthChallengeDispositionGSQCSo15NSURLCredential__T___T in Alamofire.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

It does work when I open Alamofire.xcworkspace so it must be some configuration in my project? Any idea?

Using delegates closures

I presume various closure-typed properties in SessionDelegate, TaskDelegate, DataTaskDelegate and DownloadTaskDelegate are intended to be used by clients to extend/override particular delegates behavior. If I get this right I see following issues in the current version:

  1. Can't find a way to use these closures – both Manager.delegate and Request.delegate are currently inaccessible through public API (the later is even explicitly marked as private)
  2. Some of the SessionDelegate's delegate methods don't take into account related task delegate behavior:
  3. SessionDelegate's didReceiveChallenge doesn't check if specific task delegate actually handled auth challenge, so the fallback to session-level handling doesn't work.
  4. Some of the SessionDelegate's closures are unused:

does not work in release mode (Xcode 6 beta 6)

When I run the example app in release mode I get the following EXC_BREAKPOINT. Based on my debugging, this happens whenever join() is called in release mode.

Thread 1Queue : com.apple.main-thread (serial)
#0  0x00000001004409cc in specialization <Swift.Character.SmallUTF16 with Swift.Character.SmallUTF16 : Swift.SequenceType, Swift.IndexingGenerator<Swift.Character.SmallUTF16> with Swift.IndexingGenerator<Swift.Character.SmallUTF16> : Swift.GeneratorType> of Swift._StringCore.extend (inout Swift._StringCore)<A : Swift.SequenceType>(A) -> () ()
#1  0x0000000100440760 in Swift.String.append (inout Swift.String)(Swift.Character) -> () ()
#2  0x0000000100435ca0 in protocol witness for Swift._ExtensibleCollectionType.init <A : Swift._ExtensibleCollectionType>(Swift._ExtensibleCollectionType.Self.Type)() -> Swift._ExtensibleCollectionType.Self in conformance Swift.String : Swift._ExtensibleCollectionType [inlined] ()
#3  0x0000000100435c68 in specialization <Swift.String with Swift.String : Swift.ExtensibleCollectionType, Swift.Array<Swift.String> with Swift.Array<Swift.String> : Swift.SequenceType, Swift.IndexingGenerator<Swift.String> with Swift.IndexingGenerator<Swift.String> : Swift.GeneratorType, Swift.Character, Swift.String.Index with Swift.String.Index : Swift.ForwardIndexType, Swift.Int with Swift.Int : Swift._SignedIntegerType, Swift.Int, Swift.Int with Swift.Int : Swift._BuiltinIntegerLiteralConvertible, Swift._DisabledRangeIndex_, Swift.Character, Swift.IndexingGenerator<Swift.Array<Swift.String>> with Swift.IndexingGenerator<Swift.Array<Swift.String>> : Swift.GeneratorType> of Swift.join <A : Swift.ExtensibleCollectionType, B : Swift.SequenceType>(A, B) -> A ()
#4  0x0000000100425824 in Alamofire.Manager.(defaultHeaders.getter : Swift.Dictionary<Swift.String, Swift.String>).(closure #1).(closure #1) at /Users/kriswallsmith/Developer/Alamofire/Source/Alamofire.swift:154
#5  0x0000000100407a34 in Alamofire.Manager.(defaultHeaders.getter : Swift.Dictionary<Swift.String, Swift.String>).(closure #1) [inlined] at /Users/kriswallsmith/Developer/Alamofire/Source/Alamofire.swift:144
#6  0x0000000100407a2c in Alamofire.Manager.defaultHeaders.getter : Swift.Dictionary<Swift.String, Swift.String> at /Users/kriswallsmith/Developer/Alamofire/Source/Alamofire.swift:139
#7  0x00000001003fd478 in Alamofire.Manager.request (Alamofire.Manager)(ObjectiveC.NSURLRequest) -> Alamofire.Request at /Users/kriswallsmith/Developer/Alamofire/Source/Alamofire.swift:193
#8  0x000000010041a108 in Alamofire.request (Alamofire.Method, Swift.String, parameters : Swift.Optional<Swift.Dictionary<Swift.String, Swift.AnyObject>>, encoding : Alamofire.ParameterEncoding) -> Alamofire.Request at /Users/kriswallsmith/Developer/Alamofire/Source/Alamofire.swift:926
#9  0x000000010006b9e0 in iOS_Example.MasterViewController.(prepareForSegue (iOS_Example.MasterViewController) -> (ObjectiveC.UIStoryboardSegue, sender : Swift.Optional<Swift.AnyObject>) -> ()).(requestForSegue #1) (ObjectiveC.UIStoryboardSegue) -> Swift.Optional<Alamofire.Request> at /Users/kriswallsmith/Developer/Alamofire/Example/MasterViewController.swift:67
#10 0x000000010006a960 in iOS_Example.MasterViewController.prepareForSegue (iOS_Example.MasterViewController)(ObjectiveC.UIStoryboardSegue, sender : Swift.Optional<Swift.AnyObject>) -> () [inlined] at /Users/kriswallsmith/Developer/Alamofire/Example/MasterViewController.swift:73
#11 0x000000010006a874 in @objc iOS_Example.MasterViewController.prepareForSegue (iOS_Example.MasterViewController)(ObjectiveC.UIStoryboardSegue, sender : Swift.Optional<Swift.AnyObject>) -> () ()
#12 0x0000000186a22924 in -[UIStoryboardSegueTemplate _perform:] ()
#13 0x0000000186584824 in -[UITableView _selectRowAtIndexPath:animated:scrollPosition:notifyDelegate:] ()
#14 0x00000001866416c0 in -[UITableView _userSelectRowAtPendingSelectionIndexPath:] ()
#15 0x00000001864deab8 in _applyBlockToCFArrayCopiedToStack ()
#16 0x00000001864508f4 in _afterCACommitHandler ()
#17 0x0000000181dde388 in __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ ()
#18 0x0000000181ddb314 in __CFRunLoopDoObservers ()
#19 0x0000000181ddb6f4 in __CFRunLoopRun ()
#20 0x0000000181d09664 in CFRunLoopRunSpecific ()
#21 0x000000018ad3b5a4 in GSEventRunModal ()
#22 0x00000001864c2164 in UIApplicationMain ()
#23 0x000000010006d4e8 in top_level_code [inlined] at /Users/kriswallsmith/Developer/Alamofire/Example/AppDelegate.swift:26
#24 0x000000010006d498 in main ()
#25 0x0000000192046a08 in start ()

Keeps crashing in release build (Xcode 6 Beta 6, targeting Mac OS X)

Hi Matt,

First of all, thanks for the effort of going through creating this :) I am currently using Alamofire in a Mac OS X project (targeting 10.9 for now) instead of iOS (what most if not all seem to be using).

When I add Alamofire as a git submodule to my project all works fine when I run it from within Xcode. Initially I had the image not found issues (similar to #55, #64 and #75) but I was able to solve that by adding Alamofire to the Embedding libraries (under General) and changing Alamofire's Base SDK (in build settings) to Latest OS X (OS X 10.10) and its Deployment Target to 10.9.

While all runs fine from within Xcode, I am still having issues with the Release Build crashing. Specifically on the following line:

Alamofire.request(.GET, "http://localhost:\(port)/xmlstats.do")

I am not sure why it is crashing, so hopefully you can shed some light on the issue...

This is the (part of the) stack trace:

Process:         MyApp [84129]
Path:            /Users/USER/Desktop/MyApp.app/Contents/MacOS/MyApp
Identifier:      com.something.MyApp
Version:         1.1.0 (1)
Code Type:       X86-64 (Native)
Parent Process:  launchd [491]
Responsible:     MyApp [84129]
User ID:         68009012

Date/Time:       2014-09-03 08:49:58.713 +0200
OS Version:      Mac OS X 10.9.4 (13E28)
Report Version:  11
Anonymous UUID:  000-000-000-000

Sleep/Wake UUID: 000-000-000-000

Crashed Thread:  0  Dispatch queue: com.apple.main-thread

Exception Type:  EXC_BAD_INSTRUCTION (SIGILL)
Exception Codes: 0x0000000000000001, 0x0000000000000000

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   com.alamofire.Alamofire         0x000000010618f29c _TTSVOSs9Character10SmallUTF16S0_Ss12SequenceType_GVSs17IndexingGeneratorS0__GS2_S0__Ss13GeneratorType___TFVSs11_StringCore6extendfRS_USs12SequenceType_USs13GeneratorType__FQ_T_ + 588
1   com.alamofire.Alamofire         0x000000010618f037 _TFSS6appendfRSSFOSs9CharacterT_ + 1191
2   com.alamofire.Alamofire         0x0000000106182741 _TTSSSSSSs24ExtensibleCollectionType_GSaSS_GSaSS_Ss12SequenceType_GVSs17IndexingGeneratorSS_GS1_SS_Ss13GeneratorType_OSs9Character_VSS5IndexS4_Ss16ForwardIndexType_SiSiSs18_SignedIntegerType_Si_SiSiSs33_BuiltinIntegerLiteralConvertible_VSs20_DisabledRangeIndex__S3__GS1_GSaSS__GS1_GSaSS__S2____TFSs4joinUSs24ExtensibleCollectionType_Ss12SequenceType_USs13GeneratorType__Ss16ForwardIndexType_Ss18_SignedIntegerType__Ss33_BuiltinIntegerLiteralConvertible___S1___FTQ_Q0__Q_ + 2577
3   com.alamofire.Alamofire         0x000000010616d5b3 _TFFFC9Alamofire7Managerg14defaultHeadersGVSs10DictionarySSSS_U_FT_GS1_SSSS_U_FT_SS + 1731
4   com.alamofire.Alamofire         0x000000010614cc32 _TFC9Alamofire7Managerg14defaultHeadersGVSs10DictionarySSSS_ + 66
5   com.alamofire.Alamofire         0x0000000106141864 _TFC9Alamofire7Manager7requestfS0_FCSo12NSURLRequestCS_7Request + 196
6   com.alamofire.Alamofire         0x0000000106161488 _TF9Alamofire7requestFTOS_6MethodSS10parametersGSqGVSs10DictionarySSPSs9AnyObject___8encodingOS_17ParameterEncoding_CS_7Request + 600
7   com.something.MyApp                 0x0000000105dc5032 _TFC10MyApp18MyAppInstance7refreshfS0_FFT_T_T_ + 1042 (MyAppInstance.swift:47)

And the snippet from line 47 causing the crash:

        Alamofire.request(.GET, "http://localhost:\(port)/xmlstats.do")
        .authenticate(HTTPBasic: "test", password: "test")
        .responseString { (request, response, string, error) in
              ...
        }

Cheers, Jeroen

Request delegates lifecycle

As far as I can see in the current version every request gets its own delegate instance (of appropriate type) which is then used by the Manager to handle NSURLSession delegate callbacks. Therefore every delegate instance is retained by the Manager instance through .delegate > .subdelegates chain. This relation never gets broken, so every delegate instance is kept in memory at least until Manager instance is deallocated – typically long after related request is completed. Since delegates use non-trivial amount of memory (to store response data) this causes significant memory overuse.

Idiomatic JSON serializing & deserializing

Would there be any interest in integrating a more idiomatic form of JSON serialization that also leverages some of Swift's benefits, rather than using NSJSONSerialization? If so, would it make more sense to use an existing project like SwiftyJSON, or to write something specifically for AlamoFire?

NSJSONWritingOptions.Type allZeros compile error

On Xcode 6 Beta 5, compiling the example app shows an error in the following line of code. Has anyone else seen this as well?

        let options = NSJSONWritingOptions.allZeros

The error reported in XCode is: "NSJSONWritingOptions.Type does not have a member named allZeros."

json parameters error

I have a parameter like this
let parameters = [
"username":1,
"password":"password",
"data": [1]
]
I use request method to do that
let req = Alamofire.request(.POST, "http://localhost:8080/framework-test/api/user/test", parameters: parameters, encoding: Alamofire.ParameterEncoding.JSON(options: nil))
but have a compile error
'String' is not identical to 'NSObject'
because data is a array,and array contains int ,not String .
how to deal with it?

I am chinese , im not good at english.

How to POST just a string

What is the syntax to just POST a string of JSON?

I'm having trouble getting my serialized objects to send to a server as it seems like the parameter needs to be in [key: value] format to send data, where as I am using this class to serialize my objects.

Best,

Setting header values?

I see defaultHeaders in the Manager, but I don't see a clear way of adding to this dictionary. Anyone know?

Getting started helping out

Are there instructions on setting up Alamofire for development? I'm new to XCode and it informs me "Xcode does not support opening folders without a project or workspace."

I'd like to get into the library, make some changes, and ensure all the tests pass, but I've not had luck setting it up.

Thanks

can't use on iOS Device

I can't user Alamofire With iOS Device . The error is "Library not loaded: @rpath/Alamofire.framework/Alamofire"
How to solve the problem

Why dispatch_sync?

What's the purpose of this dispatch sync? Wont it block anyway?

var dataTask: NSURLSessionDataTask?
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
    dataTask = self.session.dataTaskWithRequest(mutableRequest)
}

Linker errors, build target either 7.1 or 8

I've added the Alamofire project as a sub-project, and include the product as a framework and target dependency. The linker fails whether I am building for iOS 7.1 or 8, regardless of the target architecture. Looks like casting issues, so probably Swift or a configuration problem. Anything stand out here?

Build target Alamofire

Undefined symbols for architecture armv7:
  "__TFSs15_arrayForceCastU___FGSaQ__GSaQ0__", referenced from:
      __TFFFC9Alamofire7Managerg14defaultHeadersGVSs10DictionarySSSS_U_FT_GS1_SSSS_U_FT_SS in Alamofire.o
  "__TFSs21_arrayConditionalCastU___FGSaQ__GSqGSaQ0___", referenced from:
      __TFC9Alamofire7Request18cURLRepresentationfS0_FT_SS in Alamofire.o
  "_swift_stdlib_compareNSStringDeterministicUnicodeCollation", referenced from:
      __TFCC9Alamofire7Request12TaskDelegate10URLSessionfS1_FTGSQCSo12NSURLSession_4taskGSQCSo16NSURLSessionTask_19didReceiveChallengeGSQCSo28NSURLAuthenticationChallenge_17completionHandlerGSQFTOSC36NSURLSessionAuthChallengeDispositionGSQCSo15NSURLCredential__T___T_ in Alamofire.o
  "__TFSs26_forceBridgeFromObjectiveCU__FTPSs9AnyObject_MQ__Q_", referenced from:
      __TFC9Alamofire7Request12authenticatefDS0_FT9HTTPBasicSS8passwordSS_DS0_ in Alamofire.o
      __TFCC9Alamofire7Request12TaskDelegate10URLSessionfS1_FTGSQCSo12NSURLSession_4taskGSQCSo16NSURLSessionTask_19didReceiveChallengeGSQCSo28NSURLAuthenticationChallenge_17completionHandlerGSQFTOSC36NSURLSessionAuthChallengeDispositionGSQCSo15NSURLCredential__T___T_ in Alamofire.o
      __TFC9Alamofire7Request18cURLRepresentationfS0_FT_SS in Alamofire.o
      __TFFFC9Alamofire7Managerg14defaultHeadersGVSs10DictionarySSSS_U_FT_GS1_SSSS_U0_FT_SS in Alamofire.o
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Xcode Beta 7 compatibility

Today, Apple released Xcode 6 Beta 7, which includes a number of breaking changes involving Foundation APIs and implicitly unwrapped optionals.

Needless to say, Alamofire no longer compiles.

Getting error when testing on iOS 7 device

I am getting this error in the output when I test my app using iPhone 5S running on iOS 7.1.2.

dyld: Symbol not found: _NSURLAuthenticationMethodHTTPBasic
Referenced from: /private/var/mobile/Applications/9FDCA5E2-94CE-49CC-8925-8B3EE74F9057/Pickle 1.app/Frameworks/Alamofire.framework/Alamofire
Expected in: /System/Library/Frameworks/CFNetwork.framework/CFNetwork
in /private/var/mobile/Applications/9FDCA5E2-94CE-49CC-8925-8B3EE74F9057/Pickle 1.app/Frameworks/Alamofire.framework/Alamofire

The app works perfectly on iOS Simulator, iOS 8 and on iOS 7.1 deployment target.

Thanks.

Singleton initialization

With the access control capability is not better use a private global constant variable instead of the struct thing to store the singleton?
In this way we can go from:

public class var sharedInstance: Manager {
    struct Singleton {
        static let instance = Manager()
    }

    return Singleton.instance
}

to:

private let sharedInstance = Manager()

public class var sharedInstance:Manager {
     return sharedInstance
}

has described by the team itself in a discussion on the Apple forum (third response in the thread)the global variable will be lazy instatiated with the use of dispatch_once. To me the code is much cleaner with the static variable that with the struct.

Test setup

From Xcode 6 beta 4, there is a protect level to restrict code access from outside of the module. One biggest impact is it is hard to write tests now. I noticed there are good tests for Alamofire, but I failed to setup them for Xcode 6 beta 4.

I have tried to create a framework or application target for the Alamofire.swift and then add the test files to the test target. While I can import the framework/application module and modify Alamofire.swift by adding public to the methods needs to be accessed from test target, I was stuck in this error below when compiling the test target:

snip20140804_1

I also tried this pull request but with the same error.

(BTW: I am on OS X 10.9.4 with Xcode 6 beta 4)

I wonder is there a good way for setting up tests for Alamofire? Any suggestion will be appreciated. Thank you.

Use of unresolved identifier 'Alamofire'

I was using the previous version of Alamofire in beta 5 of Xcode. Today I uninstalled beta 5, installed beta 6 and deleted the old Alamofire file and added the latest one.

But I get this error wherever I have used Alamofire.

Use of unresolved identifier 'Alamofire'

I cleaned and built the project several times. Restarted the Mac but no avail. Does anyone else facing this issue?

POST-ing a "body" instead of parameters?

This is a great library that's going to make writing networking code so much simpler!

I didn't spot an easy way to POST a body of non-standard type (e.g., XML or protobuf). Would it make sense to add a way to pass in an data or a string along with a custom Content-Type header to allow this use-case?

Example:

Alamofire.request(.POST,  "http://httpbin.org/post",  data: data, contentType: "application/xml")

Alternatively, how about allowing a way to extend ParameterEncoding so that user can write their own serialization code to encode a Swift object into string etc.?

Consider public access

Right now, Alamofire uses the default access control qualifier, internal. Other targets in a project, such a unit tests, might want to access these internal classes, too (to make requests, for instance). I'm a bit unsure which classes, extensions, and functions should be public and which ones left internal.

Related to #42.

Alamofire framework isn't compatible with iOS7

Since embedded dylibs/frameworks only run on iOS 8 or later, is there going to be implementation for compiling a standard framework or static lib or are you planning to remove support for iOS7?

How Alamofire handle SSL

Hi! I tried calling an API which has https scheme using NSURLSession but it failed with the following error.

NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

Then I tried the same with Alamofire and it worked with no errors.

Upon further investigation, I found that implementing the following delegate method of NSURLSession can bypass the SSL errors.

public func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((disposition: NSURLSessionAuthChallengeDisposition, credential: NSURLCredential!) -> Void)!) 

Can somebody please explain is this the method used in Alamofire as well? I inspected the source file and saw its been mentioned. When I implemented this method I had to explicitly specify the host name. How does Alamofire handle it without depending on the host name?

JSON response as Dictionary<String, NSObject>

What do you think of returning the JSON response "as Dictionary<String, NSObject>" instead of the raw NSDictionnary?

The result could be then read straight with "JSON["somefield"]!". Happy to do a pull request it it gets merged.

Apple Mach-O Linker Error

Hi there, please don't mind me being a total newbie with regards to Alamofire, so this question might sound dumb to some people. :)

When I link the framework it as described (and as shown in the demo project for that matter) the only think I'm getting is weird Apple Mach-O Linker Errors, such as these:

Undefined symbols for architecture i386:
"TFSs15_arrayForceCastU___FGSaQ__GSaQ0", referenced from:
TFFFC7FCUtils7Managerg14defaultHeadersGVSs10DictionarySSSS_U_FT_GS1_SSSS_U_FT_SS in Alamofire.o
"_TFSs21_arrayConditionalCastU___FGSaQ__GSqGSaQ0
", referenced from:
__TFC7FCUtils7Request18cURLRepresentationfS0_FT_SS in Alamofire.o
"_TFSs26_forceBridgeFromObjectiveCU__FTPSs9AnyObject_MQ__Q", referenced from:
_TFC7FCUtils7Request12authenticatefDS0_FT9HTTPBasicSS8passwordSS_DS0 in Alamofire.o
_TFCC7FCUtils7Request12TaskDelegate10URLSessionfS1_FTGSQCSo12NSURLSession_4taskGSQCSo16NSURLSessionTask_19didReceiveChallengeGSQCSo28NSURLAuthenticationChallenge_17completionHandlerGSQFTOSC36NSURLSessionAuthChallengeDispositionGSQCSo15NSURLCredential__T___T in Alamofire.o
__TFC7FCUtils7Request18cURLRepresentationfS0_FT_SS in Alamofire.o
__TFFFC7FCUtils7Managerg14defaultHeadersGVSs10DictionarySSSS_U_FT_GS1_SSSS_U0_FT_SS in Alamofire.o
"_swift_stdlib_compareNSStringDeterministicUnicodeCollation", referenced from:
_TFCC7FCUtils7Request12TaskDelegate10URLSessionfS1_FTGSQCSo12NSURLSession_4taskGSQCSo16NSURLSessionTask_19didReceiveChallengeGSQCSo28NSURLAuthenticationChallenge_17completionHandlerGSQFTOSC36NSURLSessionAuthChallengeDispositionGSQCSo15NSURLCredential__T___T in Alamofire.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I even created a new Swift file in my project and copy pasted the contents of the original Alamofire.swift class into it, with the same results unfortunately. I therefore suspect that this isn't an issue related to a linked library, though I can't say for sure.

The strange thing is, the project compiles just fine for the iOS Device target, but fails when I select a simulator.

Any help would be highly appreciated. Using the latest XCode 6 beta 6 btw.

Can't run on devices

When I try to run the example (or my own project) on a device, I get this error:

dyld: Library not loaded: @rpath/Alamofire.framework/Alamofire
Referenced from: /private/var/mobile/Containers/Bundle/Application/96CA297A-883A-49F5-B639-BC9C524726FE/iOS Example.app/iOS Example
Reason: image not found

(Basic) Authentication not working

I'm trying the examples from the page:

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

    let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
    let protectionSpace = NSURLProtectionSpace(host: "httpbin.org", port: 80, `protocol`: "https", realm: "Fake Realm", authenticationMethod: NSURLAuthenticationMethodHTTPBasic)

    Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password")
        .authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
        .response {(request, response, _, error) in
            println(request.allHTTPHeaderFields)
            println(response)
    }

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

In both cases I'm getting a 401, regardless of the version of authenticate() that I use. I am targeting iOS 7.1 so I changed the project target. Thanks.

Basic Auth not Working Xcode 6 B6

Hi! currently I am using Xcode6 beta 6 and my code is below

let request = Alamofire.request(Alamofire.Method.GET, "http://nurane.otkur.biz/api/v1/address").authenticate(HTTPBasic: "azmet", password: "123456")

        .responseJSON {(request, response, JSON, error) in
            println(JSON)
            println(response)
             println(error)
            //  var err:NSError?
            var jsonResult = JSON as NSDictionary
            // var Data=jsonResult["data"] as NSDictionary
            // println("daadsfas")
            // println(Data)
            //   let results: NSArray = jsonResult ["data"] as NSArray
            //println(results)

            self.delegate.setAPIResult(jsonResult , isFirst: isFirst)
    }

and it is returnig this error bellow
Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x78f74320 {NSDebugDescription=Invalid value around character 0.})
fatal error: unexpectedly found nil while unwrapping an Optional value

and I also tried this
.responseString { (request, response, string, error) in

but always returnig
Optional("Authentication failed") error
this url is works fine in android and objective-C
I have also tried in post man it`s good
what is the problem ? thanks for ur helping

Error with parameters adding to the request

I needed this request format to be built.

{
  "DeviceCredentials": {
    "UniqueId": "sample string 1"
  },
  "Personalnumber": "sample string 1"
}

Below is my result,

let parameters = [
    "DeviceCredentials": ["UniqueId": uniqueID],
    "Personalnumber": personalNumber
]

Both uniqueID and personalNumber are of String type. I get no error at this point but when I try to add it to the request,

Alamofire.request(.POST, "https://www.example.com/api/", parameters: parameters, encoding: .JSON(options: nil)).responseJSON { (request, response, JSON, error) -> Void in
    println(JSON!)
}

I get this error at the parameters parameter,
'String' is not identical to 'NSObject'.

Is there something wrong with my format or is this a bug?

NilLiteralConvertible issue

I have added Alamofire as a framework and it builds successfully.

Here's my code,

let parameters: [String: AnyObject] = ["UniqueId": uniqueId]

Alamofire.request(.POST, "example.com/api", parameters: parameters, encoding: .JSON(options: nil)).responseJSON {(request, response, JSON, error) in

}

I get this error.
(options: NilLiteralConvertible) -> $T13' is not identical to 'ParameterEncoding

How do I resolve this?

Type Safe-ish URL's

In the spirit of increased type safety, consider a protocol as follows:

protocol URL {
    func url() -> String
}

and instead of the convenience request method taking a String for the URL parameter, it would take a struct or class conforming to the URL protocol, and retrieve the actual string URL from the protocol method.

This would "suggest" to people that they should have defined objects for whatever endpoints they need for their app, rather than just typing in random strings all over the place.

Problem running Alamofire on device running iOS 7

Has anyone been able to run Alamofire.swift on a device running iOS 7?

For me, it's crashing with:

dyld: Library not loaded: @rpath/Alamofire.framework/Alamofire
Referenced from: /var/mobile/Applications/A59259D8-0AF7-43AD-AC21-2A0530B26B09/Stayful.app/Stayful
Reason: image not found

Method names

I like where Alamofire is going! But a quick feedback: I'm a bit confused with the method names that are not verbs:

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

Do you have any suggestions on alternative names?

By the way, a similar question: what do you see as the advantage of Chainable Request / Response methods? Could someone show me an example that clearly shows the advantage?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.