Swift 2 error, converting to JSON - ios

Ive been having an error with swift 2, its so simple but i cant get it
Here's the code before I started updating it for Swift 2:
func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let url = "http://api.openweathermap.org/data/2.5/forecast"
let params = ["lat":latitude, "lon":longitude]
println(params)
Alamofire.request(.GET, url, parameters: params)
.responseJSON { (request, response, json, error) in
if(error != nil) {
println("Error: \(error)")
println(request)
println(response)
self.loading.text = "Internet appears down!"
}
else {
println("Success: \(url)")
println(request)
var json = JSON(json!)
self.updateUISuccess(json)
}
}
}
here's the line throwing error:
let json = JSON(json)
Here's the whole func after i started
func updateWeatherInfo(latitude: CLLocationDegrees, longitude: CLLocationDegrees) {
let url = "http://api.openweathermap.org/data/2.5/forecast"
let params = ["lat":latitude, "lon":longitude]
print(params)
Alamofire.request(.GET, url, parameters: params)
.responseJSON { (request, response, json) in
print("Success: \(url)")
print(request)
let json = JSON(json)
self.updateUISuccess(json!)
}
}
updateUISuccess requires a JSON value, but at the moment I have a (Request )
heres the error description
After a suggestion I tried this:
.Success(let data):
let data_ar = data as! JSON // or NSDictionary or NSString
self.updateUISuccess(data_ar)
case .Failure(let data, let error):
print("Request failed with error: \(error)")
}
but the app crashes at let data_ar = data as! JSON // or NSDictionary or NSString

The variable json looks like an enum value. Try this:
switch json {
case .Success(let data):
let data_ar = data as! NSArray // or NSDictionary or NSString
case .Failure(let data, let error):
print("Request failed with error: \(error)")
}

Related

How to grab the Optional response in swift?

I want to grab the ImagePath from the response.
Response look like this
The response for print(response.result.value)
I am using Alamofire POST request to get the data from Api. Here is my code:
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
if response.result.error != nil {
}
let Response = response.result.value
print("Response JSON:- \(String(describing: Response))")
let mydata = (String(describing : Response))
let jSon = JSON(mydata)
print("New :- \(String(describing: jSon["data"]["ImagePath"].stringValue))")
print("New :- \(jSon["data"]["ImagePath"])")
print(jSon["data"]["ImagePath"])
print(jSon["status"].stringValue)
if let data = response.result.value {
let json = JSON(data)
//print(json)
}
}
Try optional handling this way
if let Response = response.result.value as? [String : Any],
myData = Response["data"] as? [String : Any],
imgPath = myData["ImagePath"] {
print("ImagePath --> ", imgPath)
}

cannot extract JSON

Hello I am trying to extract a json. However I am getting an error saying Cannot convert value of type 'Data' to expected argument type 'NSData'. Is there something that I am doing wrong?
success: { (response) -> Void in
var dataStream: Data = Data.init(referencing: response!)
do {
let data = try JSONSerialization.jsonObject(with: dataStream, options: JSONSerialization.ReadingOptions.mutableContainers)as AnyObject
}catch{
}
if let id = response!["money"]as? String {
print(id)
}
}){ (error) -> Void in
print("error")
}
}
Update2
let request = Alamofire.request(apiUrl, method: .get)
request.responseJSON { response in
switch response.result
{
case .success:
success(response.result.value as AnyObject)
case .failure(let error):
failure(error as NSError)
}
}
}
Your problem is here
var dataStream: Data = Data.init(referencing: response!)
in Docs
init(referencing reference: NSData)
response should be of type NSData not Data , you may try
let responseDict = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
note cast to expected return whether it's dictionary or array
this
if let id = response!["money"]as? String {
print(id)
}
should be replaced with
if let id = responseDict!["money"]as? String {
print(id)
}
You can try Alamofire with SwiftyJson
Alamofire.request("https://yourlinkdownloadjson/abc").responseJSON { response in
debugPrint(response)
if let json = response.data {
let data = JSON(data: json)
print("data\(data["money"])")
}
}

error in return response 'cannot call value of non-function type 'NSHTTPURLResponse?' with Swift 3

I read answer from other questions also but not able to solve:
I tried with following way but getting same error at the line of
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
please help us in how you add #escaping in following method.
public func JSONResponseObject<T: ResponseObjectSerializable>(_ completionHandler: #escaping (DataResponse<T>) -> Void) -> Self {
let responseSerializer = DataResponseSerializer<T> { request, response, data, error in
guard error == nil else { return .failure(error!) }
let jsonResponseSerializer = DataRequest.jsonResponseSerializer(options: .allowFragments)
let result = jsonResponseSerializer.serializeResponse(request, response, data, nil)
print("result: \(result.value)")
switch result {
case .success(let value):
let json = JSON(value)
print("JSON: \(json)")
if let
response = response,
let responseObject = T(response: response, representation: value as AnyObject)
{
return .success(responseObject)
} else {
let error = Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: -6006 as! Error)
return .failure(error as! Error)
}
case .failure(let error):
let json = JSON(error)
print("JSON: \(json)")
return .failure(error)
}
}
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
}
I solved now in following way
I set extension DataRequest { } instead in extension Request { }

Alamofire4 trouble with JSONResponseSerializer & HTTPURLResponse Swift 3.0

Since I updated Alamofire I get the errors: Type Request has no member JSONResponseSerializer and cannot call value of non-function type HTTPURLResponse
I have already switched Response to DataResponse but I still get the error.
Code:
extension Alamofire.Request {
func responseUserEventsArray(_ completionHandler: #escaping (DataResponse<UserEventsWrapper>) -> Void) -> Self {
let responseSerializer = DataResponseSerializer<UserEventsWrapper> { request, response, data, error in
guard error == nil else
{
return .failure(error!)
}
guard let responseData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .allowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, responseData, error)
switch result {
case .Success(let value):
let json = JSON(value)
let wrapper = UserEventsWrapper()
wrapper.next = json["eventhistory"]["next_page_url"].stringValue
wrapper.previous = json["eventhistory"]["prev_page_url"].stringValue
wrapper.count = json["eventhistory"]["total"].intValue
var allUserEvents:Array = Array<UserEvents>()
print(json)
let results = json["eventhistory"]["data"]
print(results)
for jsonAds in results
{
print(jsonAds.1)
let adsData = UserEvents(json: jsonAds.1, id: Int(jsonAds.0))
allUserEvents.append(adsData)
}
wrapper.usereventsitems = allUserEvents
return .success(wrapper)
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer,completionHandler: completionHandler)
}
}
EDITED
Change
Request.JSONResponseSerializer to DataRequest.jsonResponseSerializer
extension Alamofire.Request to extension Alamofire.DataRequest – Mat0
.success and .failure - FranMowinckel

Alamofire Completion Handler returning response + data

I have a function that includes a responseObject in it's completion handler. At the moment this returns the json body when I call it, along with any errors.
Some parts of the API I am using however, don't return any data in the response body, they just return a response (200, 404, etc...)
I was thinking about appending the response inside the empty json object that is getting returned, then realised that would be silly and it would probably be better if I returned the NSHTTPURLResponse as well, but everything I have found just explains how to return the responseObject along with the error...
This is the function that returns the completion handler:
func makePostRequest(url : String, params : AnyObject, completionHandler: (responseObject: NSHTTPURLResponse, JSON?, error: NSError?) -> ()) -> Request? {
println("params = \(params)")
return Alamofire.request(.POST, url, parameters: params as? [String : AnyObject], encoding: .JSON)
.responseJSON { (request, response, data, error) in completionHandler(
//This is wrong
response: response as? NSHTTPURLResponse,
responseObject:
{
println("Request is \(request)")
println("Response is \(response)")
println("Data is \(data)")
println("Error is \(error)")
//Append the response to this JSON object?
//
var json:JSON = [:]
if let anError = error
{
println(error)
}
else if let data: AnyObject = data
{
json = JSON(data)
}
//probably better to return the two...
//
return (response, json)
}(),
error: error
)
}
}
And this is how its used:
networking.makePostRequest(documentUrl, params: docParams) { response, json, error in
println("response is: \(response)")
println("document json: \(json)")
println("document error: \(error)")
}
I've added in the 'response' bits to all the bits of code, i'm sure this is possible? just not sure how to achieve it..
For anyone stuck trying to figure out how to return stuff this way, I solved it like this:
func makePostRequest(url : String, params : AnyObject, completionHandler: (httpResponse: NSHTTPURLResponse, responseObject:JSON?, error: NSError?) -> ()) -> Request? {
println("params = \(params)")
return Alamofire.request(.POST, url, parameters: params as? [String : AnyObject], encoding: .JSON)
.responseJSON { (request, response, data, error) in completionHandler(
//This is wrong
httpResponse: response!,
responseObject:
{
println("Request is \(request)")
println("Response is \(response)")
println("Data is \(data)")
println("Error is \(error)")
//Append the response to this JSON object?
//
var json:JSON = [:]
if let anError = error
{
println(error)
}
else if let data: AnyObject = data
{
json = JSON(data)
}
return json
}(),
error: error
)
}
}
and then calling it like this:
networking.makePostRequest(workDocumentUrl, params: params) { response, json, error in
if response.statusCode == 200{
//do something
}
println("json: \(json)")
println("error: \(error)")
}

Resources