Alamofire
Elegant HTTP Networking in Swift
Fresh vanilla submodule install of Alamofire, using XCode6 and following directions to a T. Something here just isn't fitting right. The error i'm getting is "Could not build objective-c module "alamofire" on import alamofire. Here is a screen shot of the error i'm getting:
And my configuration:
Source: (StackOverflow)
Following code I have written and I am getting response in JSON also but the type of JSON is "AnyObject" and I am not able to convert that into Array so that I can use that. Please help as it is very urgent.
Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
(request, response, JSON, error) in
println(JSON?)
}
Source: (StackOverflow)
I follow the instructions to the T. Fresh install of all, yet getting the error:
"No Such module Alamofire"
Directions here:
In the meantime, you can simply add Alamofire as a git submodule, drag the Alamofire.xcodeproj file into your Xcode project, and add the framework product as a dependency for your application target.
And my screenshots
Source: (StackOverflow)
I am just starting to take a look at Mattt's wonderful new Alamofire swift networking library and am not quite sure how one would use it with custom headers.
The code i am trying to convert from AFNetworking to Alamofire is this:
let request = NSMutableURLRequest(URL: url)
request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")
Source: (StackOverflow)
how is it possible to send a POST request with a simple string in the HTTP body with Alamofire in my iOS app?
As default Alamofire needs parameters for a request:
Alamofire.request(.POST, "http://mywebsite.com/post-request", parameters: ["foo": "bar"])
These parameters contain key-value-pairs. But I don't want to send a request with a key-value string in the HTTP body.
I mean something like this:
Alamofire.request(.POST, "http://mywebsite.com/post-request", body: "myBodyString")
Source: (StackOverflow)
I'm using Alamofire in a Swift project, and part of their manual installation instructions are to add Alamofire under Embedded Binaries in the General tab for my application target.
What are Embedded Binaries?
Source: (StackOverflow)
My question is quite similar to this one, but for Alamofire : AFNetworking: Handle error globally and repeat request
How to be able to catch globally an error (typically a 401) and handle it before other requests are made (and eventually failed if not managed) ?
I was thinking of chaining a custom response handler, but that's silly to do it on each request of the app.
Maybe subclassing, but which class should i subclass to handle that ?
Source: (StackOverflow)
I wonder if it's possible to directly send an array (not wrapped in a dictionary) in a POST request. Apparently the parameters
parameter should get a map of: [String: AnyObject]?
But I want to be able to send the following example json:
[
"06786984572365",
"06644857247565",
"06649998782227"
]
Source: (StackOverflow)
I am trying to find the solution for simple processing all necessary steps for read-only consuming remote JSON data on iOS devices. It means fetching remote JSON data, store to local cache on iOS device for offline usage, refresh the cache, parsing JSON data. I think it is very common requirement for all mobile apps nowadays.
I know it is possible to manually download remote JSON file, store it to local db or file on iOS device and when network is not available fetch it from local storage otherwise dowload it from net. I do it manually now. :) But it is lot of steps which hope is possible to do by using frameworks/libraries, isn't?
So I tried HanekeSwift framework which do almost everything what I need but it only do caching remote JSON (and Images) but doesn't refresh the cache!! which is not useful for me. I know also that exists Alamofire and SwiftyJSON but I don't have any experience with them.
Do you have any experience how to do that?
Summary
- libraries or frameworks for iOS8 support in Swift
- download remote JSON and store to local cache
- possibility to refresh local cache from it's origin
- nice bonus is easy JSON parsing
Thank you! Michal
Source: (StackOverflow)
I've read couple tutorials, README from @mattt but can't figure out couple things.
What is the proper usage of URLRequestConvertible
in real world API? It looks like if I will create one router by implementing URLRequestConvertible
protocol for all API - it will be barely readable. Should I create one Router per endpoint?
Second question most likely caused by lack of experience with Swift language. I can't figure out why enum
is used for building router? Why we don't use class with static methods?
here is an example (from Alamofire's README)
enum Router: URLRequestConvertible {
static let baseURLString = "http://example.com"
static let perPage = 50
case Search(query: String, page: Int)
// MARK: URLRequestConvertible
var URLRequest: NSURLRequest {
let (path: String, parameters: [String: AnyObject]?) = {
switch self {
case .Search(let query, let page) where page > 1:
return ("/search", ["q": query, "offset": Router.perPage * page])
case .Search(let query, _):
return ("/search", ["q": query])
}
}()
let URL = NSURL(string: Router.baseURLString)!
let URLRequest = NSURLRequest(URL: URL.URLByAppendingPathComponent(path))
let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
}
}
There are 2 ways to pass parameters:
case CreateUser([String: AnyObject])
case ReadUser(String)
case UpdateUser(String, [String: AnyObject])
case DestroyUser(String)
and (say user has 4 parameters)
case CreateUser(String, String, String, String)
case ReadUser(String)
case UpdateUser(String, String, String, String, String)
case DestroyUser(String)
@mattt is using the first one in the example. But that will lead to "hardcoding" parameters' names outside the router (e.g. in UIViewControllers).
Typo in parameter name can lead to error.
Other people are using 2nd option, but in that case it not obvious at all what each parameter represents.
What will be the right way to do it?
Source: (StackOverflow)
I'm experiencing some strange behaviour with my test app. I've about 50 simultaneous GET requests that I send to the same server. The server is an embedded server on a small piece of hardware with very limited resources. In order to optimize the performance for each single request, I configure one instance of Alamofire.Manager
as follows:
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPMaximumConnectionsPerHost = 2
configuration.timeoutIntervalForRequest = 30
let manager = Alamofire.Manager(configuration: configuration)
When I send the requests with manager.request(...)
they get dispatched in pairs of 2 (as expected, checked with Charles HTTP Proxy). The weird thing though is, that all requests which didn't finish within 30 seconds from the first request, get cancelled because of the timeout at the same time (even if they haven't been sent yet). Here is an illustration showcasing the behaviour:
Is this an expected behaviour and how can I make sure that the requests won't get the timeout before they are even sent?
Thanks a lot!
Source: (StackOverflow)
I'm trying to configure Alamofire to follow redirects (or not) on a per-request basis.
Alamofire has a private internal class SessionDelegate
which serves as the NSURLSessionTaskDelegate
for the current URL session. SessionDelegate
does implement the relevant delegate method, URLSession(session:, task:, willPerformHTTPRedirection response:, request:, completionHandler:)
which is exactly what I want.
Even better, the delegate's implementation consults a custom variable closure named taskWillPerformHTTPRedirection
to determine how to handle the redirect - again, exactly what I want!
And as far as I can tell, that closure is always nil
by default -- it is not assigned to internally by Alamofire -- which suggests that it is intended to let the user assign a closure to it.
The problem: I cannot access this private SessionDelegate
class to assign a closure to its taskWillPerformHTTPRedirection
variable. It is a private class and it is not visible to my Swift files. What is the proper means of configuring an Alamofire request to (not) follow redirects?
Source: (StackOverflow)
I am attempting to upload a file using Alamofire. The upload works fine when using a File (NSURL), however, I cant seem to figure out how to use the NSDATA option?
This is what I have as a test:
var url:NSURL = NSURL.URLWithString("http://localhost:8080/bike.jpeg")
var err: NSError?
var imageData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
Alamofire.upload(.POST, "http://localhost:8080/rest/service/upload/test.png", imageData)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
println(totalBytesWritten)
}
.responseJSON { (request, response, JSON, error) in
println(request)
println(response)
println(JSON)
}
I am getting a status code 415?
Also, how can I send across additional params in the upload?
Thanks
EDIT
I wasn't setting the correct Content-Type:
var manager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = ["Content-Type": "application/octet-stream"]
let imageData: NSMutableData = NSMutableData.dataWithData(UIImageJPEGRepresentation(imageTest.image, 30));
Alamofire.upload(.POST, "http://localhost:8080/rest/service/upload?attachmentName=file.jpg", imageData)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
println(totalBytesWritten)
}
.responseString { (request, response, JSON, error) in
println(request)
println(response)
println(JSON)
}
Still cant figure out how to send additional parameters along with the upload.
Source: (StackOverflow)
class APIClient {
var user = User()
let alamoFireManager : Alamofire.Manager?
let center = NSNotificationCenter.defaultCenter()
init(){
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 4 // seconds
configuration.timeoutIntervalForResource = 4
self.alamoFireManager = Alamofire.Manager(configuration: configuration)
}
func test(){
//This does not respect the 4 second time out. Why?
self.alamoFireManager!.request(.POST, CONSTANTS.APIEndpoint+"/test", parameters: parameters).responseJSON {
(req, res, json, error) in
if let json = self.handleAPIResponse(req, res: res, json_data: json, error: error){
}
}
}
Source: (StackOverflow)
I have a question about the new version of Alamofire for Swift 2
Alamofire.request(.POST, urlString, parameters: parameters as? [String : AnyObject])
.responseJSON { (request, response, result) -> Void in
let dico = result as? NSDictionary
for (index, value) in dico! {
print("index : \(index) value : \(value)")
}
}
In this section I would like to cast the result in to a NSDictionary. But When I compile and put a breakpoint, the debugger says that dico is nil. If I use debugDescription to print result, it is not nil and contains what I expected
How can I cast the Result variable?
Source: (StackOverflow)