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

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.

Related

Alamofire iOS13

I want to update my code in the past when I used swift 2 or 3. I am stuck where I want to use Alamofire but the way to use it changed and I don't know how to use it anymore. Can anybody update this part of the code and explain a little bit? Thank you.
This is the original code.
Alamofire.request(.POST, url)
.response{ (request, response, data, error) in
let xml = SWXMLHash.parse(data!)
let sunsetTime = xml["result"]["rise_and_set"]["sunset_hm"].element?.text
self.sunsetTimeLabel.text = sunsetTime
self.getDateFromString(sunsetTime,year: comp.year,month: comp.month,day: comp.day)
if (error != nil) {
print(error)
}
}
this is the code I was writing.
AF.request(url, method: .post).responseJSON { (responseData) in
let xml = SWXMLHash.parse(responseData as Data)
let sunsetTime = xml["result"]["rise_and_set"]["sunset_hm"].element?.text
self.sunsetTimeLabel.text = sunsetTime
There is an error saying "Cannot convert value of type 'AFDataResponse' (aka 'DataResponse') to type 'Data' in coercion"
Your first code snippet is Alamofire 3 syntax. I infer from the second code snippet that you are now using Alamofire 5.
There are a few issues:
You are calling responseJSON (which you’d only use if your response was JSON, not XML). Use response or, better, responseData.
The response object passed to this closure is not a Data, itself. In the case of responseData method, it is a AFDataResponse object, which has a data property (which is a Data?). You have to extract the Data object from this AFDataResponse, either by unwrapping the contents of the data property, or from the result (see next point).
You should probably check for success or failure and extract the Data from the response.result object.
So, pulling this together, you end up with something like:
AF.request(url, method: .post).responseData { response in
switch response.result {
case .failure(let error):
print(error)
case .success(let data):
let xml = SWXMLHash.parse(data)
...
}
}

Print data from Alamofire request, swift

I made this request:
func AlamofireGetCode()
{
let username: String = searchTextField.text!
var url:String!
url = "https:// ... "
AF.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success:
debugPrint(response)
case .failure(let error):
fatalError("\(error)")
}
}
}
And I'm getting this response with different fields:
[Result]: success({
"incomplete_results" = 0;
items = (
{
"username" = " ... "
...
How do I get some specific field like "username" in Swift?
I would like to have all the username of all the user and store them, could you help me?
You need to provide a type to parse the JSON response into. Using a site like quicktype.io can generate one from your JSON, but any Decodable type will do. Then you can use Alamofire's responseDecodable handler to parse your response.
AF.request(url).responseDecodable(of: TypeToParse.self) { response in
debugPrint(response)
}
Paste your response in https://jsonparseronline.com/ to see the structure of the object. It will show you all the keys and values that you can access using subscripts.

Alamofire HTTP sent twice SWIFT

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

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.

How to install properly Alamofire SwiftyJSon and Alamofire-SwiftyJson

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.