Has you can see from my previous questions, I got a lot of trouble parsing JSON Data. After few days of headache with that, I think the best way still to use alamofire/swiftyjson. I also found the alamofire-swiftyjson to let everything working well together.
But I am not sure how to install this three "libraries" together.
I download the whole Alamofire pack inside my project, I add the SwiftyJson.swift in my project and finally download the Alamofire-SwiftyJson in my project.
But when I change my alamofire request with "responseSwiftyJSON" I get an error saying " "Request" does not have a member name "responseSwiftyJSON
Alamofire.request(.GET, "http://mysiteweb.com/app/data/jsonpersodata.php", parameters: ["username": username]).responseSwiftyJSON { (request, response, data, error)
Add Alamofire and SwiftyJSON to the project. Then you can use Alamofire to request the data from the server and SwiftyJSON for serialization.
Alamofire 4
Alamofire.request(url).responseJSON { response in
guard let data = response.data else {
// No data returned
return
}
let json = JSON(data: data)
print(json)
}
Alamofire 3
Alamofire.request(.GET, url).validate().responseJSON { response in
switch response.result {
case .Success:
if let jsonData = response.result.value {
let json = JSON(jsonData)
print(json)
}
case .Failure(let error):
print(error)
}
}
Alamofire 2
Alamofire.request(.GET, "http://api.example.com", parameters: ["username" : username])
.responseJSON { request, response, data, error in
let swiftyJSONObject = JSON(data: data!)
}
Note that you have to unwrap data because server may return nothing.
Related
I am trying to see what is the latest and greatest way to retrieve json data in swift 4 (using Codable structure).
I have the following json data in a remote url:
[
{
"products": [
{
"productid": "01",
"price": "01"
},
{
"productid": "02",
"price": "02"
}
]
}
]
I have also setup the corresponding codable structure. My questions is what would be the correct way to retrieve this data using the latest techniques for swift 4.
I am seeing various ways such as:
DataManager.getJSONFromURL ...
let jsonData = try Data(contentsOf: URL ...
let task = URLSession.shared.dataTask(with: url) ...
try JSONSerialization.data...
I would like to know which is the correct (latest) format for retrieving json data using swift 4 from a remote URL. Thank you.
I found the answer to my question.
Apple announced Swift 4 as part of Xcode 9 at WWDC 2017. It brings some really nice improvements to existing Swift 3 features as well as stability. The latest ways of working with REST API in Swift 4 is using URLSession and JSONDecoder. The later was introduced with Swift 4.
In Swift 3, most of developers used third party frameworks such as SwiftyJson and Alamofire in order to work with REST APIs. The reason for this, most of the time, was that parsing JSON using Swift was very tedious. More precisely - you had to set up initializer in your Model, had to do loops to assign values in your controller, had to typecast values and so on. You could always copy/paste your code, but still it was overwhelming. With Swift 4 all you will need to do is to write just a single line to decode and parse JSON.
URLSession and JSONDecoder are all you need in Swift 4 for retrieving json data from a remote url.
For more information and an example, you can check this site:
URLSession and JSONDecoder in Swift 4
func getRequestWithUrl(url : String ,onCompletionHandler : #escaping ([String : Any]?) -> Void){
let headers : HTTPHeaders = [
"X-Api-Key": "EPE67704498C76B16CF29B956B2A2E91",
"Accept": "application/json",
]
Alamofire.request(url, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
switch response.result {
case .success:
onCompletionHandler(response.result.value as? [String : Any])
break
case .failure(_):
onCompletionHandler(nil)
}
}
}
we have an API which allows us to create a new board with a title “New
York Highlights”. For this, using Alamofire the code is very easy:
AF.request("https://api.mywebserver.com/v1/board", method: .get, parameters: ["title": "New York Highlights"])
.validate(statusCode: 200..<300)
.responseDecodable { (response: DataResponse) in
switch response.result {
case .success(let board):
print("Created board title is \(board.title)") // New York Highlights
case .failure(let error):
print("Board creation failed with error: \(error.localizedDescription)")
}
}
For Alamofire you need to install framework for more detail read this document
Doing exactly the same with the URLSession API requires a bit more of
work.
enum Error: Swift.Error {
case requestFailed
}
// Build up the URL
var components = URLComponents(string: "https://api.mywebserver.com/v1/board")!
components.queryItems = ["title": "New York Highlights"].map { (key, value) in
URLQueryItem(name: key, value: value)
}
// Generate and execute the request
let request = try! URLRequest(url: components.url!, method: .get)
URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
guard let data = data,
let response = response as? HTTPURLResponse, (200 ..< 300) ~= response.statusCode,
error == nil else {
// Data was nil, validation failed or an error occurred.
throw error ?? Error.requestFailed
}
let board = try JSONDecoder().decode(Board.self, from: data)
print("Created board title is \(board.title)") // New York Highlights
} catch {
print("Board creation failed with error: \(error.localizedDescription)")
}
}
credit
I am trying to get image from server using Alamofire. It is working in postman ref:attachement
Below is my code for reference:
let headers = ["Authorization" : APITOKEN,"Content_Type" : CONTENT_TYPEVAL]
Alamofire.request(urlString!, method: .get, parameters: nil, encoding: URLEncoding.default, headers:headers ).responseJSON { (response) in
switch response.result {
case .success(let origObject):
debugPrint(origObject)
if let object = origObject as? Dictionary<String,AnyObject>
{
}
completion(.failure(Ya3ClientError.serverUnknownError))
case .failure(let e):
debugPrint("error:\(e.localizedDescription)")
}
Getting error "JSON could not be serialized because of error:\nThe data couldn’t be read because it isn’t in the correct format."
Any help how to solve this issue.
Instead of using .responseJson, you can try using .responseData to get a Data object and create the image using UIImage(data:)
Take a look at this
You can create a UIImage from a Data object, which you get from the response with Alamofire. However, without seeing your JSON response I cannot help with the exact code. If the response only contains the image as its data, then you can use
Alamofire.request(.GET, "https://myUrl/myPicture.png").response { (request, response, data, error) in
myImageView.image = UIImage(data: data)
}
You can also have a look at the Alamofire Image library.
I'm very new to Swift 3, and i have to do a GET request on my API. I'm using Alamofire, which uses Asynchronous functions.
I do exactly the same on my Android App, and the GET returns JSON data
This is my code in swift :
func getValueJSON() -> JSON {
var res = JSON({})
let myGroup = DispatchGroup()
myGroup.enter()
Alamofire.request(url_).responseJSON { response in
res = response.result.value as! JSON
print("first result", res)
myGroup.leave()
}
myGroup.notify(queue: .main) {
print("Finished all requests.", res)
}
print("second result", res)
return res
}
But i have a problem with the line "res = response.result.value" wich gives me the error : Thread 1 : signal SIGABRT
I really don't understand where the problem comes from, it was pretty hard to do a "synchronous" function, maybe i'm doing it wrong.
My objective is to store the result of the request in a variable that i return. Anyone can help ?
I'd recommend you to use Alamofire together with SwiftyJSON because that way you'll be able to parse JSON easier a lot.
Here's a classical example:
Alamofire.request("http://example.net", method: .get).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
case .failure(let error):
print(error)
}
}
If you need to pass parameters, or headers, just add it in the request method.
let headers: HTTPHeaders = [
"Content-Type:": "application/json"
]
let parameters: [String: Any] = [
"key": "value"
]
So your request will be something like this (this is POST request):
Alamofire.request("http://example.net", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
switch response.result {
case .success(let value):
print(value)
case .failure(let error):
print(error)
}
}
I haven't tested it, but it should work. Also, you need to set allow arbitary load to yes (App Transport Security Settings in info.plist) if you want to allow requests over HTTP protocol.
This is NOT recommended, but it's fine for development.
I get the following error since I upgraded to Xcode 8:
Extra Argument In A Call
My code looks like this:
Alamofire.request(.GET, link).validate().responseJSON { response in
The error highlights link in red. It is defined further above the code:
let link = "http://www.gov.je/_layouts/15/C5.Gov.Je.CarParks/proxy.aspx"
Why do I get this error?
According to the document:
- Data Request - Simple with URL string
// Alamofire 3
Alamofire.request(.GET, urlString).response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
// Alamofire 4
Alamofire.request(urlString).response { response in // method defaults to `.get`
debugPrint(response)
}
So you need to remove .GET argument
let link = "http://www.gov.je/_layouts/15/C5.Gov.Je.CarParks/proxy.aspx"
Alamofire.request(link).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
every one,
I'm having an issue with Alamofire 3.0, when I post data, it seems the data is being sent twice.
I looked up on the web, found that a bug about special caratères was fixed, but I still get the error.
Anyone has an idea. I'm using a parameter in the header called X-Authorization.
Here is an extract of the code i'm using:
static func postData (url: String,token: String,params :Dictionary<String,AnyObject>){
print("POSTINGGGGGG")
Alamofire.request(.POST, url, parameters: params,headers: ["X-Authorization": token])
.responseJSON { response in
switch response.result {
case .Success(let data): break
//let resultJSON = JSON(data).dictionaryValue
// print(data)
case .Failure(let error):
print(error)
}
}
}
Thank you in advance,
Morgan