mark mark - 6 months ago 24
Swift Question

Getting nil value when passing value to api

Things i did :


  1. I have one url api which will display some data in my table view.
    2.And i fetch the particular value called "_id" from my url and i just pass that value to one custom class object.

  2. Then i am passing that class object value to one of my another api calling url.In there i getting the value as nil.



Here is the code that ia m populating the data to my table view.And i am taking the particular value from api "_id" And i am storing that value to one custom class object :

// Showing favourites
func populateFavourites()
{
let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String

let headers = ["x-access-token": token]

let request = NSMutableURLRequest(URL: NSURL(string: "some url")!)
request.HTTPMethod = "GET"
request.allHTTPHeaderFields = headers

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in

if (error != nil)
{
print(error)
}
else
{
dispatch_async(dispatch_get_main_queue(),{
if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
{

print("Success Got Json Data")

let success = json["success"] as? Int

if(success == 1)
{
let jsonData = json["data"] as! NSArray

if(jsonData.count>0)
{



for items in jsonData
{
let BObj = items as! NSDictionary

let BusinessDetails = BObj.valueForKey("business_id") as! Dictionary<String,AnyObject>

self.FavBusinessValues.append(Businessdata(json:BusinessDetails))
print(items)

let FavId = BObj.valueForKey("_id") as! String


self.FavDelete?.FavIds = FavId

print(FavId)




}

self.tableView.reloadData()

}
else
{
self.CreateNoDataLabel()
}
}
else
{
let message = json["message"] as? String

print("Fav Message ",message)

let alert = UIAlertController(title: "Error: ", message: message, preferredStyle: UIAlertControllerStyle.Alert)

// add an action (button)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

// show the alert
self.presentViewController(alert, animated: true, completion: nil)
}
}
})
}
})
dataTask.resume()

}


In my above code i am taking the particular value "_id" and i am passing to my custom objet class :

let FavId = BObj.valueForKey("_id") as! String
self.FavDelete?.FavIds = FavId
print(FavId)


This
print(FavId)
is printing the correct value.Here is my cutom class object that store that value of "_id" :

import Foundation
class Favdelete
{
var FavIds : String?


init(json:String)
{

self.FavIds = json as? String

}
}


Then i am passing the "_id" objet value
FavIds
to my one of my api calling.That code is under below :

func apidelete () {



let Favouriteid = FavDelete?.FavIds
print(Favouriteid)

let userToken = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String;
print(userToken)


let headers = [
"x-access-token": userToken,
"cache-control": "no-cache",
"postman-token": "81fbd1fc-c333-3ceb-272a-a9ecffb2dad2",
"content-type": "application/x-www-form-urlencoded"
]




let FBI = "favourite_id="+Favouriteid!


let postData = NSMutableData(data: FBI.dataUsingEncoding(NSUTF8StringEncoding)!)

let request = NSMutableURLRequest(URL: NSURL(string: "some url")!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? NSHTTPURLResponse
print(httpResponse)
dispatch_async(dispatch_get_main_queue(),{
if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
{

print("Success Got Json Data");

let success = json["success"] as? Int;

var message:String = "";

if(success == 1)
{
message = json["message"] as! String;
}
else
{
message = json["message"] as! String;
}

print(message);

let alert = UIAlertController(title: "Message from server", message: message, preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

self.presentViewController(alert, animated: true, completion: nil)

}
})

}
})

dataTask.resume()




}


When i try to print this :

let Favouriteid = FavDelete?.FavIds
print(Favouriteid)


I ma getting crash and it says nil printing in my console.

Can any one please help me out.!!

Updated :

Under my first function method.That is when i get the particular value and store that value to my custom object .I just print it.I am getting nil there too.

The line is :

let FavId = BObj.valueForKey("_id") as! String
self.FavDelete?.FavIds = FavId
print(self.FavDelete?.FavIds)


Its printing nil

Updated :

enter image description here

enter image description here

Answer

Although you have a custom class you need to initialize it to use its method. Without proper initialization you cannot set its properties. So in the ViewController, declare the object for that class at the top. var FavbDelete : Favdelete? At this point, your FavDelete is nil.

Then you get the "_id" from populateFavourites() method. You may be calling it from viewDidLoad() method. There you get FabId as let FavId = BObj.valueForKey("_id") as! String But now you cannot directly store it into FabDelete Object. because it has not been initialized. Although Xcode doesn't throw any error when you do that, But the resulting value will be nil. So now you initialize that object using the initializer you built in custom class.

self.FavDelete = Favdelete(json: FavId)

Now the FavDelete object is initialized , and when you call apidelete() method after this step, you can access the value of id by using

let someVar = self.FavDelete?.FavIds

Since, all of this work is being done in background using NSURLSession,ensure that you are not calling apidelete before the FabDelete Object is initialized.

Comments