Comments (19)
Parsing client specific JSON is beyond the scope of this library, and is a responsibility placed on the specific client. SwiftyJSON is built in a way that lets you turn the JSON object returned from Alamofire into a JSONValue
very easily.
Write a class that wraps Alamofire, providing custom GET, POST, etc. methods and use the .response() methods to call a success or failure block as appropriate for your code, passing along the JSON.
from alamofire.
Parsing client specific JSON is beyond the scope of this library, and is a responsibility placed on the specific client.
Well said, @justinmakaila.
Though I would say the easiest way to integrate would be to implement a responseSwiftyJSON
method in an extension on Alamofire.Request.
from alamofire.
I almost forgot about how wonderfully easy it is to do things like that in Swift. Changing my own implementation now!—
Sent from Mailbox
On Tue, Aug 26, 2014 at 2:12 PM, Mattt Thompson [email protected]
wrote:
Parsing client specific JSON is beyond the scope of this library, and is a responsibility placed on the specific client.
Well said, @justinmakaila.Though I would say the easiest way to integrate would be to implement a
responseSwiftyJSON
method in an extension on Alamofire.Request.Reply to this email directly or view it on GitHub:
#57 (comment)
from alamofire.
responseSwiftyJSON ~~thanks
from alamofire.
Has anyone actually done this?
Having a hard time since JSONValue is of type enum, an does not conform to AnyObject. Is there an easy way to implement this?
Could Alamofire make it easier to implement, by allowing Any
in Request.response instead of AnyObject
..
from alamofire.
I have an implementation, I can post it later tonight—
Sent from Mailbox
On Sat, Sep 20, 2014 at 6:19 PM, Lars-Jørgen Kristiansen
[email protected] wrote:
Has anyone actually done this?
Having a hard time since JSONValue is of type enum, an does not conform to AnyObject. Is there an easy way to implement this?
Reply to this email directly or view it on GitHub:
#57 (comment)
from alamofire.
import Alamofire
// MARK: Alamofire Extensions
typealias AlamofireResponseCompletionBlock = (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void
typealias APIResourceResponseCompletionBlock = (NSURLRequest, NSHTTPURLResponse?, JSONValue?, NSError?) -> Void
typealias APICollectionResponseCompletionBlock = (NSURLRequest, NSHTTPURLResponse?, [JSONValue]?, Int?, NSError?) -> Void
internal extension Alamofire.Request {
func collectionResponseJSON(completionHandler: APICollectionResponseCompletionBlock) -> Self {
let completion: AlamofireResponseCompletionBlock = { request, response, JSON, error in
var jsonData: JSONValue!,
results: [JSONValue]?,
nextCursor: Int!,
requestError: NSError?
if let data: AnyObject = JSON {
jsonData = JSONValue(data)
if error != nil {
requestError = self.serializeRequestError(jsonData, error: error!)
} else {
results = jsonData["results"].array
nextCursor = jsonData["nextCursor"].integer
}
}
dispatch_async(dispatch_get_main_queue(), {
completionHandler(request, response, results, nextCursor, (requestError != nil) ? requestError! : error)
})
}
return response(
priority: 0,
queue: APIManager.sharedInstance().callbackQueue,
serializer: Request.JSONResponseSerializer(),
completionHandler: completion
)
}
func resourceResponseJSON(completionHandler: APIResourceResponseCompletionBlock) -> Self {
let completion: AlamofireResponseCompletionBlock = { request, response, JSON, error in
var jsonData: JSONValue!,
requestError: NSError?
if let data: AnyObject = JSON {
jsonData = JSONValue(data)
if error != nil || response?.statusCode >= 300 {
requestError = self.serializeRequestError(jsonData, error: error)
}
}
dispatch_async(dispatch_get_main_queue(), {
completionHandler(request, response, jsonData, (requestError != nil) ? requestError! : error)
})
}
return response(
priority: 0,
queue: APIManager.sharedInstance().callbackQueue,
serializer: Request.JSONResponseSerializer(),
completionHandler: completion
)
}
/**
* Attempts to serialize error json into an NSError object.
* @discussion If `json` is nil, returns `error`
*
* @param json JSONValue representing the error
* @param error NSError that came back from Alamofire
*
* @return NSError with JSON error serialized in userInfo["APIError"]
*/
private func serializeRequestError(json: JSONValue?, error: NSError?) -> NSError? {
var apiError: Error?,
requestError: NSError? = error
if let jsonError: JSONValue = json {
apiError = Error(json: jsonError)
}
if apiError != nil {
requestError = NSError(domain: "APIManagerErrorDomain", code: apiError!.code ?? -1111, userInfo: [
"APIError": apiError!
])
}
return requestError
}
}
from alamofire.
^ @iUtvikler
from alamofire.
@justinmakaila Works great! Thanks
from alamofire.
I have been looking since a days on "How to parse JSON response from Alamofire API in Swift?" but didn't get the answer yet! Please take a look on the below code and let me know what has o be done in this regard.
Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON) .responseJSON
{
(request, response, JSON, error) in
println(JSON?)
}
I am able to print the response but cannot assign in Dictionary or Array. Why so?
How can I parse the response from this method?
from alamofire.
I use something like the following. I'm not sure if it's the best way of doing it, but it seems to work for me.
Alamofire.request(.POST, "MY URL", parameters:parameters, encoding: .JSON)
.responseJSON { (request, response, json, error) in
if let object = json as? NSDictionary {
println(object)
}
}
This gives you a non-optional constant called object
that you can then do with as you will.
It does however mean you have to know if your base structure is an array or a dictionary, so there are probably better ways of doing it to make it more abstract.
from alamofire.
Thanks for your answer!
I tried that and I am able to print that object also but still I am facing issues in assigning the value from the Dictionary in the String form.
I am getting following response
{
message = "succesfull login";
sid = "";
status = 1;
}
and I am trying something like this.
if var dictionary = JSON as? NSDictionary
{
println(dictionary) //1
println(dictionary.objectForKey("status")) //2
var temp:String = dictionary.objectForKey("status") //2
}
On line //3, I am getting following error,
Cannot convert the expression's type 'StaticString' to type 'AnyObject'
How can I store value in String so that I can use that? Why this all is so complex?
from alamofire.
You should take a look at https://github.com/SwiftyJSON/SwiftyJSON
there is also an extension to work with Alamofire
https://github.com/SwiftyJSON/Alamofire-SwiftyJSON
from alamofire.
You have to take it out as a string. So try something like the following.
var temp = dictionary.objectForKey("status") as? String
This will give you an optional String variable in temp
.
I might be wrong but this type of questioning might be better moved to StackOverflow or similar places. As issues for Git repos are normally more for issue/bugs with the framework rather than use issues.
from alamofire.
I tried this
var temp = dictionary.objectForKey("status") as? String
and it is returning nil but there is a value for the key "status".
Yes, I should ask that on Stackoverflow and I have posted my questions over there but nobody responded. That is why I here as I downloaded Alamofire from here.
And my question is very simple and I am surprised why nobody can answer this.
from alamofire.
@violabg
https://github.com/SwiftyJSON/Alamofire-SwiftyJSON
I downloaded that but SwiftJSON folder is empty and seems files are missing
Can you please let me know how can I use that?
from alamofire.
@harshcs My guess would be look into submodules in Git, I think that would be why you have an empty folder.
I've just noticed that your "status"
value is an integer in the sample JSON you provided, not a String
as you're trying to cast it as. So taking it out and casting as a String will return nil
as it can't find a String
so it returns nil
. Try the following to get an optional Int
:
let temp = dictionary.objectForKey("status") as? Int
Make sure you always double check what type the JSON value is. If you want to make it into a string this you could do something like the following:
let tempString = String(temp)
from alamofire.
@Baza207 aka James! 👍
Thanks a lot Baza! Actually server side developer sending the Bool value and internally it was getting converted in the Integer form but now it is working as I put a check for the Int value and its not Nil anymore. You saved me! :-)
from alamofire.
@harshcs can you describe the implementation that you did.
I am newbie to swift and Alamofire
from alamofire.
Related Issues (20)
- Multiple AF.upload cannot be concurrent HOT 1
- App crash on archived version HOT 1
- Different iOS minimal OS support in Package.swift and Alamofire.podspec HOT 1
- Upload Progress called only once with fraction value 1.0 before the upload request complete HOT 2
- Dr
- Add Conformance To ClientTransport From swift-openapi-generator HOT 1
- Timeout responseCode is nil HOT 2
- Add support for visionOS HOT 1
- New version with privacy manifest is not available HOT 3
- Crash - CompositeEventMonitor.request<A>(_:didParseResponse:) HOT 1
- The macOS deployment target 'MACOSX_DEPLOYMENT_TARGET' is set to 10.10, but the range of supported deployment target versions is 10.13 to 14.2.99. (in target 'Alamofire macOS' from project 'Alamofire') HOT 1
- In Xcode's InspectorView, Signature's Kind is Unsigned HOT 1
- Crash on startup with Alamofire 4.9.1 HOT 1
- Cocoapods support for visionOS HOT 4
- Authenticator with Swift Concurrency HOT 3
- Almofire SDK privacy details not reflecting in my project HOT 20
- Not possible to `validate` `WebSocketRequest`? HOT 2
- WebSocketRequest Should Support Validation
- Request for Alamofire Dependency Update to Support Privacy Manifest in AlamofireObjectMapper SDK HOT 1
- Build test target failed with release 5.9
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from alamofire.