Print a specific value from ios UITABLEVIEW - ios6

SOffer[26229:c07] current Product: (
{
id = 20;
image = "img2.png";
name = "offer 2";
}
)
I have product which result the above when I print it through NSLog,, I need to print the these individually. Following code generate this
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
NSString *currentProductName;
currentProductName = [productKeys objectAtIndex:indexPath.row];
currentProduct = [products objectForKey:[productKeys objectAtIndex:indexPath.row]];
NSLog(#"current Product: %#",currentProduct);
//currentProductName = [currentProduct objectForKey:#"image"];
//currentProduct = [currentProduct ];
[[cell textLabel] setText:currentProductName];
return cell;
}
currentProduct is declared as NSArray but when i try to print with objectForKey it say No visible interface for NSArray declares the selector ObjectForKey

objectForKey, I believe works with NSDictionary only.
NSArray does not have key value pairs. Unless currentProduct holds the JSON file, then you gonna have to first get out the Array Object of the first Product and assign it to a NSDictionary, where you can then use the objectForKey to get your image value.
Something like this:
// Get the first product object from the NSArray. Assuming you dropped your entire Product values into a NSArray
NSMutableDictionary *prodDict = [currentProduct objectAtIndex:indexPath.section];
NSString *prodID = [prodDict objectForKey:#"id"];
NSString *prodName = [prodDict objectForKey:#"name"];
...

Related

Append to array in UserDefaults

First I import the existing array saved in user defaults in key - array1
var savedArray = UserDefaults.standard.array(forKey: "array1") as! [String]
var ns = UserDefaults.standard
Then
let savedValue = name
Then
savedArray.append(savedValue!)
Then I save it in key - array1
UserDefaults.standard.set(savedArray, forKey: "array1")
And sync
ns.synchronize()
However, if I go into another viewcontroller and do this
let alreadyShownarray = UserDefaults.standard.object(forKey: "array1") as! [String]
print (alreadyShownarray)
Then I get the same array without the appended savedValue!
Try removing the object and adding the new one.
UserDefaults.standard.removeObject(forKey: "array1")
UserDefaults.standard.set(savedArray, forKey: "array1")
You can fetch the array, assign it to a variable, append your element, then set the object for the same key that you used to fetch.
func enqueue(localNotificationModel: LocalNotificationModel) {
guard let localNotificationJSON = UserDefaults.standard.value(forKey: localNotificationKey) as? [[String: Any]] else { return }
var localNotifiactions = localNotificationJSON.compactMap { LocalNotificationModel(json: $0)}
localNotifiactions.append(localNotificationModel)
UserDefaults.standard.set(localNotifiactions, forKey: localNotificationKey)
}
You cannot update the Array directly from NSUserDefault. you have to create a new arrray and assign the existing array from NSUserDefault then you can set that new array to the NSUserDefault one
var newArray = [String]() //2.create a new array and assign the UserDefault array1 here
var ns = UserDefaults.standard
let savedArray = ns.array(forKey: "array1") as! [String] //1.this is protected cannot update directly
let savedValue: String = "name" //3. the value you wanted to append
newArray = savedArray //4. just copying the value here
newArray.append(savedValue) //5. appending the new value
ns.set(newArray, forKey: "array1") //6. now the value "name" is saved.
// array1[0] = "your initial value"
// array1[1] = "name"

How to append an array in another array in Swift?

I have a JSON response whose answer I have to parse. I write the single elements into an array called courseDataArray using a for loop. After that, I want to write this newly created array into another array called combinedCourseArray with the aim to pass that on to a UITableView. Creating the first array seems to work fine.
But how can I create another array combinedCourseArray who contain all arrays of type courseDataArray?
for (index, element) in result.enumerate() {
// get one entry from the result array
if let courseEntry = result[index] as? [String:AnyObject]{
//work with the content of the array
let courseName = courseEntry["name"]
let courseType = courseEntry["course_type"]
let courseDate = courseEntry["cor_date"]
let courseId = courseEntry["cor_id"]
let duration = courseEntry["duration"]
let schoolId = courseEntry["sco_id"]
let status = courseEntry["status"]
let courseDataArray = ["courseName" : courseName, "courseType": courseType, "courseDate": courseDate, "courseId": courseId, "duration": duration, "schoolId":schoolId, "status":status]
print(courseDataArray)
var combinedCourseArray: [String: AnyObject] = [:]
combinedCourseArray[0] = courseDataArray //does not work -- error: cannot subscript a value of type...
// self.shareData.courseStore.append(scooter)
}
You should move the combinedCourseArray declaration outside of the array. It should be var combinedCourseArray: [[String: AnyObject]] = [[:]] since it's an array and not a dictionary.
And you should be doing
combinedCourseArray.append(courseDataArray)
instead of
combinedCourseArray[0] = courseDataArray
var FirstArray = [String]()
var SecondArray = [String:AnyObject]()
FirstArray.append(contentsOf: SecondArray.value(forKey: "key") as! [String])
First declare this combinedCourseArray array out side this loop
var combinedCourseArray: [[String: AnyObject]] = [[String: AnyObject]]()
for (index, element) in result.enumerate() {
// get one entry from the result array
if let courseEntry = result[index] as? [String:AnyObject]{
//work with the content of the array
let courseName = courseEntry["name"]
let courseType = courseEntry["course_type"]
let courseDate = courseEntry["cor_date"]
let courseId = courseEntry["cor_id"]
let duration = courseEntry["duration"]
let schoolId = courseEntry["sco_id"]
let status = courseEntry["status"]
let courseDataArray = ["courseName" : courseName, "courseType": courseType, "courseDate": courseDate, "courseId": courseId, "duration": duration, "schoolId":schoolId, "status":status]
print(courseDataArray)
combinedCourseArray.append(courseDataArray) //does not work -- error: cannot subscript a value of type...
// self.shareData.courseStore.append(scooter)
}
}
Just use flatMap on the outer array to translate one array into another array, possibly dropping some elements:
let courseDataArray : [[String:AnyObject?]] = result.flatMap {
guard let courseEntry = $0 as? [String:AnyObject] else {
return nil
}
return [
"courseName" : courseEntry["name"],
"courseType": courseEntry["course_type"],
"courseDate": courseEntry["cor_date"],
"courseId": courseEntry["cor_id"],
"duration": courseEntry["duration"],
"schoolId": courseEntry["sco_id"],
"status": courseEntry["status"]
]
}
Of course, the guard isn't really necessary since the input type is presumably already [[String:AnyObject]] and since you then can't have any internal failures, you can just use map instead of flatMap

How can i plot markers on map swift

I'm taking JSON's data and storing all geox coming from JSON in geox and geoy in geoy.
while plotting markers by for loop throws me error "cannot convert value of type NSArray to expected argument type CLLocationDegrees(aka Double)"
let data = JSON as! NSDictionary
let result = Data["result"] as! NSArray
let geox = result.valueForKey("geo_x") as! NSArray
let geoy = result.valueForKey("geo_y") as! NSArray
let count = geox.count
for index in 0...count {
let position = CLLocationCoordinate2DMake(geox,geoy)
let marker = GMSMarker(position: position)
marker.map = mapView
}
Can anyone point me in the direction to solve this?
If I understand, you receive two separate arrays : one for longitude coordinates and another for latitude.
So you can do something like that :
First replace this :
let geox = result.valueForKey("geo_x") as! NSArray
let geoy = result.valueForKey("geo_y") as! NSArray
by this :
let geox = result.valueForKey("geo_x") as! [CLLocationDegrees]
let geoy = result.valueForKey("geo_y") as! [CLLocationDegrees]
and then :
for index in 0...count {
let position = CLLocationCoordinate2DMake(geox[index],geox[index])
let marker = GMSMarker(position: position)
marker.map = mapView
}

Accessing Array Values in other instances

In my application, I am trying to access the array values but the array is return zero values. I have been stuck on this for a few hour now, and cannot seem to solve it. So any help would be appreciated:
#implementation MyScene{
NSMutableArray *_touchPoints;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint touchPoint = [[touches anyObject] locationInNode:self.scene];
[self clearTouchPoints];
[self addTouchPointToMove:touchPoint];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
CGPoint touchPoint = [[touches anyObject] locationInNode:self.scene];
CGPoint targetPoint = CGPointMake(touchPoint.x , touchPoint.y - delta.y);
[self addTouchPointToMove:touchPoint];
NSLog(#"Value: %lf", touchPoint.y);
}
- (void)move:(NSNumber *)_tempTime{
CGPoint currentPoint = [_touchPoints[0] CGPointValue];
CGPoint targetPoint = [_touchPoints[1] CGPointValue];
NSLog(#"Check Value: %lf", targetPoint.y);
}
- (void)addTouchPointToMove:(CGPoint)point {
[_touchPoints addObject:[NSValue valueWithCGPoint:point]];
}
- (void)clearTouchPoints {
[_touchPoints removeAllObjects];
}
The array is never initialized (e.g., _touchPoints = [NSMutableArray new];) so it is nil. Attempting to invoke methods on a nil object does nothing, nor does it complain (i.e., does not throw an exception). So in the addTouchPointToMove method:
[_touchPoints addObject:[NSValue valueWithCGPoint:point]];
does nothing.
In the init method, initialize the array.

Xcode Storyboard segue to pass song title from array to detail view controller

I get this error message:-[MPConcreteMediaItem isEqualToString:]: unrecognized selector sent to instance…
I am creating an NSMutable array of songs from media picker into an array named "array". This array shows up properly in the tableview (myTable). HOWEVER when I try to segue to the detail view and send the song title to a label on the detail view following this tutorial. I get the crash and error message above.
Appreciate any help, thanks!
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"detailView"]) {
NSIndexPath *indexPath = [self.myTable indexPathForSelectedRow];
DetailViewController *vc = [segue destinationViewController];
vc.trackName = [array objectAtIndex:indexPath.row];
//crashes -[MPConcreteMediaItem isEqualToString:]: unrecognized selector sent to instance
}
}
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {
[array addObjectsFromArray:mediaItemCollection.items];
[myTable reloadData];
// mediaItemCollection = nil;
[mediaPicker dismissViewControllerAnimated:YES completion:nil];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//this method is called to fill out table with data
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"Cell"];
}
// Configure the cell
anItem = nil;
anItem = [array objectAtIndex:indexPath.row];
cell.textLabel.text = [anItem valueForProperty:MPMediaItemPropertyTitle];
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;
}
The error looks like that you aren't calling 'isEqualToString:' on a string object... Which superclass has MPConcreteMediaItem

Resources