Display data from alamofire 3 + swiftyjson - swift

I'm new in Swift and iOS-dev. I'm trying to create simple app working with JSON API.
I can get and print JSON data in console:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.responseData { response in
print(response.request)
print(response.response)
print(response.result)
self.output = response.response // don't work, return nil
}
How can I display response with UITextView or UITableView? I just don't understand how to access data in closure..
Update
Looks like I miss something fundamental..:
Why it's return nil?

Related

How to get Image (not url or NSData )from server using Alamofire

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.

POST request not working in swift3 with alamofire

I am using Alamofire for calling my API .
below is is the code.
func alamofirePost() {
let headers: HTTPHeaders = [ "content-type": "x-www-form-urlencoded"]
let todosEndpoint: String = "http://54.244.108.186:4000/api/post_upc"
let newTodo: [String: Any] = ["UPC": codeTextView.text, "DATE_TIME": currentTime() ]
print("i am in alamo")
Alamofire.request(todosEndpoint, method: .post, parameters: newTodo ,encoding: JSONEncoding.default,headers: headers )
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling POST on /todos/1")
print(response)
print(response.result.error!)
return
}
when i call the function , it is trying to inserting null values in the database
INSERT INTO `UPC`(`UPC`,`DATE_TIME`) VALUES (NULL,NULL)
Below is the response when i do in postman app.
can someone please help
Firstly in your Postman request you are POSTing your body as x-www-form-urlencoded but in your Swift example you are specifying that header as well. BUT you're actually submitting your POST body as a JSON payload. In contrast, your Postman request is a set of key/value pairs.
Additionally, the two keys appear to be named differently from your Swift example and your Postman example.
Swift uses UPC and DATE_TIME while Postman has upc_app and dttm_app so at a minimum you'll want to ensure you send along what your API expects

Extra Argument In A Call

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)")
}
}

How can I retrieve the status message of a request made with Alamofire?

The server that I am using returns error messages in the HTTP status message. For example, it will return "400 User already exists" rather than "400 Bad Request".
I would like to access the string "User already exists" in the response method called by Alamofire. However, I cannot find any way to access this string.
I found this question on StackOverflow already: Swift Alamofire: How to get the HTTP response status code
Unfortunately, no one gives an answer to the question. :(
Here is where Chrome shows where the error is:
I would suggest trying to print out all the possible data fields that you are given and see what you can find. Please try the following example and see if that sheds any light.
let URL = NSURL(string: "your/url/to/somewhere")!
let parameters = ["foo": "bar"]
Alamofire.request(.POST, URL, parameters: parameters)
.response { request, response, data, error in
println("Request: \(request)")
println("Response: \(response)")
println("Error: \(error)")
if let data = data as? NSData {
println("Data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
}
}
Return response in json format from the server and then i think you'll be able to get the appropriate status.
I've implemented that thing using php codeigniter..from where my response is like
$response['status'] = 'user_already_exists';
$this->response($response, 400);
Now in swift you can go with this
Alamofire.request(.POST,URL, parameters:parameters) .responseJSON
{
(request, response, data, error) in
var json = JSON(data!) //I've used swiftyJSON for reading json response
let status = json["status"].stringValue
println("Status : \(status)")
}
Hope this may help you.

returning JSON as string in Swift using Swifty

I'm using Alamofire and Swifty and am able to make my API POST and get data back successfully. However, I'm unsure of how to get the data that I'm printing and be able to return it as a string.
In the below, the println's print fine. However, when I use the same json["ticket"] as the return, I get 'JSON' is not convertible to 'Void'
let encoding = Alamofire.ParameterEncoding.URL
// Fetch Request
Alamofire.request(.POST, "http://api.co/?v=1", parameters: bodyParameters, encoding: encoding)
.validate(statusCode: 200..<300)
.responseJSON{(request, response, data, error) in
if (error == nil)
{
var json = JSON(data!)
println(json["ticket"])
return json["TOKEN"]
}
else
{
println("HTTP HTTP Request failed: \(error)")
}
The problem is you are returning "Dictionary" from the closure, while Closure return type is Void. So, you need to get that in a completion handler.
For better idea, you can take a look at this solution. Hope it helps!