Object reference not set to an instance of an object in iOS - ios

When i am calling api with Alamofire from iOS getting error -
Object reference not set to an instance of an object
All other apis are working fine. Don't know it is from backend or not.
I debug it and check log with po command, but all parameters are going with request.
Can anyone suggest a solution ?
Any quick help will be appreciated.
Thanks
Code is given below:
let strToken: String = (USER_DEFAULT.value(forKey: "token") as? String)!
let strQuerystring = "token=" + strToken
let parameters: [String: String] = ["FirstName": txtFirstName.text!, "LastName":txtLastName.text!,"Gender":txtGender.text!,"DOB":strDate,"RelationId":strMemberID]
callPostApi(fileName: postAddMember + strQuerystring, parameters: parameters) { responseObject, errorResponse in
if(errorResponse == nil)
{
if let json = responseObject as? NSDictionary
{
let strStatus: Bool = json.value(forKey: "Status") as! Bool
let strMessage: String = json.value(forKey: "Message") as! String
if(strStatus == true)
{
forAlert(strMessage)
_ = self.navigationController?.popViewController(animated: true)
}
else
{
forAlert(strMessage)
}
}
else
{
forAlert("noResponseMessage".localized)
}
}
else
{
forAlert("noResponseMessage".localized)
}
SKActivityIndicator.dismiss()
}
}

The response object is not json, you will need to serialize it first before assigning the values to their respective variables.
something like this :
guard let dictionary = try? JSONSerialization.jsonObject(with:responseObject!,options: []) as! [String: AnyObject] else { return }
Hope that works.

You need to conform URLRequest with your parameters in body as Data
and create the request as following :
let auth = "Bearer"+token // or your Authorization type
let url = URL.init(string:urlString)
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue(auth, forHTTPHeaderField: "Authorization")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters)
Alamofire.request(request)
.responseJSON { response in
// Handling your data
}
try this and hope that help you .
you can see :
How to post nested json by SwiftyJson and Alamofire?
see also : Using manager.request with POST

You don't need to serialize the parameters. From Alamofire Docs parameters must be of type Parameters
let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
In your case import Alamofire and then declare parameters like this and do not serialize it.:
let parameters: Parameters = [
"FirstName": txtFirstName.text!,
"LastName":txtLastName.text!,
"Gender":txtGender.text!,
"DOB":strDate,
"RelationId":strMemberID
]

Related

API URL to post json formatted data

How would I transfer code from textfields into json formatted data.
Below is the current code i have, but it doesn't seem to transfer the data within the textfields to json when the button is clicked. Is their any errors within this code?
#IBAction func submitButton(_ sender: Any) {
// parse in paramaters
let parameters = ["Name": nameTextField, "Email": emailTextField, "DOB": dateTextField] as [String : Any]
guard let url = URL(string: "https://prod-69.westeurope.logic.azure.com/workflows/d2ec580e6805459893e498d43f292462/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=zn8yq-Xe3cOCDoRWTiLwDsUDXAwdGSNzxKL5OUHJPxo") else { return }
var request = URLRequest(url: url)
// let url session know that this is a post request
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// convert paramaters to JSON
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
Are nameTextField, emailTextField and dateTextField of type String or UITextField. Make sure you are passing the UITextField.text property and not the UITextField itself.
See below:
guard let name = nameTextField.text,
let email = emailTextField.text,
let dob = dateTextField.text else {
return
}
let parameters: [String: String] = ["name": name, "email": email, "dob": dob]

how to parse JSON array inside object in swift4

I'M using tableview to parsing JSON data. the parse data in tableview in successful parsed on my tableView but the problem is users click the tableview cell to pass to details ViewController.But the problem is i can't parse JSON in details ViewController in
here is my JSON looks
[
{
"id": "263",
"userId": "2692"
}
]
here is my code
guard let url = URL(string: URL API) else { return }
var request = URLRequest(url: url)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(AccessToken!)", forHTTPHeaderField: "Authorization")
request.httpMethod = "GET"
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? [string: anyobject]
print(json)
label.text = json["id"] as? string
}catch {
}
}.resume()
Please try this codes
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [[String: String]] {
for data in json {
label.text = data["id"] as? String
}
}
} catch { print(error) }
Parse json in swift4 using Codable protocol.
declare your model like this:
struct Model: Codable {
let id: Double
let userId: Double
enum CodingKeys : String, CodingKey {
case id = "id"
case userId = "userId"
}
}
then, after getting data, use this:
do {
let arrayValue = try JSONDecoder().decode([Model], from: data)
}
catch {
}
Note that your json is array not dictionary!

How to send POST request with both parameter and body for JSON data in Swift 3 using Alamofire 4?

Postman api url added below.
Present code :
let baseUrl = "abc.com/search/"
let param = [
"page":"1",
"size":"5",
"sortBy":"profile_locality"
]
let headers = [
"Content-Type": "application/json"
]
Alamofire.SessionManager.default.request("\(baseUrl)field", method: .post,parameters: param, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
print(response.request ?? "no request") // original URL request
if(response.response?.statusCode != nil){
print("done")
if self.checkResponse(response.response!.statusCode){
let json = JSON(data: response.data!)
//print("at_LeadStop json \(json)")
return completionHandler(json, false)
} else {
return completionHandler(JSON.null, true)
}
} else {
print("gone")
return completionHandler(JSON.null, true)
}}
I don't know how to add body request through this code. Please help me to slove this problem.
You are mixing two things here, page,size and sortBy is you need to pass with the url string as query string. Now your body is request is JSON Array and you can post array with Alamofire only using URLRequest. So try like this.
let baseUrl = "abc.com/search/"
let queryStringParam = [
"page":"1",
"size":"5",
"sortBy":"profile_locality"
]
//Make first url from this queryStringParam using URLComponents
var urlComponent = URLComponents(string: baseUrl)!
let queryItems = queryStringParam.map { URLQueryItem(name: $0.key, value: $0.value) }
urlComponent.queryItems = queryItems
//Now make `URLRequest` and set body and headers with it
let param = [
[
"fieldName" : "abc",
"fieldValue":"xyz"
],
[
"fieldName" : "123",
"fieldValue":"789"
]
]
let headers = [ "Content-Type": "application/json" ]
var request = URLRequest(url: urlComponent.url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: param)
request.allHTTPHeaderFields = headers
//Now use this URLRequest with Alamofire to make request
Alamofire.request(request).responseJSON { response in
//Your code
}
Try this: Using Custom Encoding
struct JSONStringArrayEncoding: ParameterEncoding {
private let array: [[String : Any]]
init(array: [[String : Any]]) {
self.array = array
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
let data = try JSONSerialization.data(withJSONObject: array, options: [])
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
return urlRequest
}
}
Calling
let values = [
[
"fieldName" : "abc",
"fieldValue":"xyz"
],
[
"fieldName" : "123",
"fieldValue":"789"
]
]
let param = [
"page":"1",
"size":"5",
"sortBy":"profile_locality"
]
let parameterEncoding = JSONStringArrayEncoding.init(array: values)
Alamofire.request("url", method: .post, parameters: param, encoding:parameterEncoding ).validate().response { (responseObject) in
// do your work
}

authenticating json data, it does not take username and password in swift? can you correct me my code?

http://beta.json-generator.com/api/json/get/E1jKVbplX I have registered successfully. i am struck in authentication. i accessed all data. but i struck in accessing individual user data. please see below code and correct me. var email = “bhupal”
var pwd = “k”
//
let parameters: Dictionary<String, AnyObject> = ["Email": email as AnyObject, "Password": pwd as AnyObject,"Type" : "Organization" as AnyObject,"Mode" : "Register" as AnyObject]
//create the url with URL
let url = URL(string: "http://beta.json-generator.com/api/json/get/E1jKVbplX ")! //change the url
let session = URLSession.shared
//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "GET" //set http method as GET
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil
{
print ("ERROR")
}
else
{
if let content = data
{
do
{
//Array
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
print("--------")
print(myJson[0])
print(myJson[1])
print("--------")
email = myJson["Email"] as? String
pwd = myJson["Password"] as? String
print("--------")
print(email)
print(pwd)
print("--------")
}
catch
{
}
}
}
}
task.resume()
Your response is Array of Dictionary so myJson[0] will return you a dictionary object and in that dictionary you should try accessing value for Email or Password.
You can try below code to access email and password :
for dict in myJson { // myJson is array and dict will of dictionary object
let email = dict[Email]
let password = dict[Password]
print("--------")
print("Email is : \(email)")
print("Password is : \(password)")
print("--------")
}
Note : You make need to improvise it.

How to successfully pass string array as parameter alamofire

I have an endpoint that accepts a string array as parameter but I can't get it working with alamofire.
I test my endpoint with postman and it works fine, even in the browser, but with alamofire it fails and just returns the whole thing (as if I didn't put any parameter).
func getQuotes(String url){
//THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX
let stringArray : [String] = ["4250_XSAU", "Test"]
let getQuoteParameters : Parameters = [
//"internal_symbols": stockInternalSymbols
"internal_symbols" : stringArray
]
print("attempting to get quotes on utility queue")
Alamofire.request(url, parameters: getQuoteParameters).responseJSON{ response in
print(response)
/* if (response.result.value != nil){
let jsonResponse = JSON(response.result.value!)
print(jsonResponse)
}
*/
}
}
Am I doing something wrong? When I go to url + "?internal_symbols=["4250_XSAU","Test"] on my browser, or postman, it works just fine.
I also tried setting my "getQuoteParamaters" variable as
let getQuoteParameters : Parameters = [
"internal_symbols" : ["4250_XSAU", "Test"]
]
but it doesn't work neither... it should be the same thing.
Just to clarify, this request ignores completely my parameters, when it should send the array to my backend.
You can simply pass your string array in converting it into a JSON format.Like in the sample code given below:
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = ["06786984572365", "06644857247565", "06649998782227"]
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
switch response.result {
case .failure(let error):
print(error)
if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
print(responseString)
}
case .success(let responseObject):
print(responseObject)
}
}
My solution in Swift 3:
let text: [String] = ["location.branches.longitude", "location.branches.latitude"]
let params: Parameters = [
"_source": text
]
Try by add encoding standard in your request, like JSONEncoding.default
func getQuotes(String url){
//THIS CALL IS NOT WORKING. PARAMETERS ARE NOT SENT PROPERLY - FIX
let stringArray : [String] = ["4250_XSAU", "Test"]
let getQuoteParameters : Parameters = [
//"internal_symbols": stockInternalSymbols
"internal_symbols" : stringArray
]
print("attempting to get quotes on utility queue")
Alamofire.request(url, method: .post, parameters: getQuoteParameters, encoding: JSONEncoding.default).responseJSON{ response in
print(response)
/* if (response.result.value != nil){
let jsonResponse = JSON(response.result.value!)
print(jsonResponse)
}
*/
}
Thanks.

Resources