how to fetch user info by uid swift 3 firebase - authentication

I am using firebase swift 3. I am new in firebase. So I build an application which user can sign up and post an event, other user can view events and click on attend button if they want to attend. Successfully I can implement all this but my problem is when user click on attend button it will save as user uid under peoplewhoattend child. now I want to view those people who will attend the event. I think I should link user uid to user profile but I can not do that. I have tried a lot and find some similar question but nothing work with me. Here is my code. Rhanks in advance for every positive comment and help
this is attend action button
#IBAction func btnAttend(_ sender: Any) {
self.btnattend.isEnabled = true
let dbRef = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
let storageRef = Storage.storage().reference(forURL: "gs://event-f39cc.appspot.com")
let key = dbRef.child("posts").childByAutoId().key
let imageRef = storageRef.child("posts").child(uid).child("\(key).jpg")
let data = UIImageJPEGRepresentation(self.imgEvent.image!, 0.5)
dbRef.child("users").child("posts").child(self.EventId!).observeSingleEvent(of: .value, with: { (snapshot) in
let updateattends = ["peopleWhoattend/\(key)" : Auth.auth().currentUser!.uid , "UserEmail" : Auth.auth().currentUser?.email , "Username" : Auth.auth().currentUser?.displayName] as [String: Any]
dbRef.child("posts").child(self.EventId!).updateChildValues(updateattends, withCompletionBlock: {(error, reff) in
if error == nil{
dbRef.child("posts").child(self.EventId!).observeSingleEvent(of: .value, with: {(snap) in
if let properties = snap.value as? [String: AnyObject] {
if let Attend = properties["peopleWhoattend"] as? [String: AnyObject]{
let count = Attend.count
self.lblattend.text = "\(count)"
let update = ["Attend" : count]
dbRef.child("posts").child(self.EventId!).updateChildValues(update)
self.btnattend.isHidden = false
// self.unlikeBtn.isHidden = false
//self.unlikeBtn.isEnabled = true
}
}
})
}
})
})
dbRef.removeAllObservers()
}
my database on firebase in JASON format
<pre>
{
"posts" : {
"-KrbDH19ERe9Os5RrEin" : {
"Attend" : 10,
"Category" : "Film & Media",
"Event date End" : "15/08/2017 10:47 PM",
"Event date Start" : "15/08/2017 10:47 PM",
"EventId" : "-KrbDH19ERe9Os5RrEin",
"EventTitle" : "hhh",
"Fee" : "6",
"Location" : {
"latitude" : 23.61349209999999,
"longitude" : 58.5434909,
"place name" : "Ruwi St, Muscat, Oman"
},
"User Email" : "salwa#hotmail.com",
"author" : "abeer",
"commentsId" : "-KrbDH19ERe9Os5RrEio",
"description" : "Event Description : dsdss",
"likes" : 3,
"pathToImage" : "https://firebasestorage.googleapis.com/v0/b/event-f39cc.appspot.com/o/events%2FhjAPqucu2jh3sY6v9n9nRM5Fuz73%2F-KrbDH19ERe9Os5RrEin.jpg?alt=media&token=795f2555-f36d-49d7-9bdd-e521fcd14c16",
"peopleWhoLike" : {
"-KrdnWbWtQ7zmkVwN7MZ" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-Krdnymu9a_zP81JFDzm" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KsZb-WL9dptWI7dHWDf" : "3IHHOBRaVyR3ldK4hGtcGoY7lox2"
},
"peopleWhoattend" : {
"-KrbDLO6ZIpIxt4lTax0" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KrbDMri-KrHDrvCAHS4" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KrbE3OppAyB_zI5XacN" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KrbE3bgAZgvLs9J2KJr" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KrbE3vSo1Z6EqOAO4SJ" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KrbE4H_kpwgsMRlRCt6" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KrbE4Xa2CP_KXC8dQbi" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KtL2Egv2slRRk8f_rF1" : "H5kCOhIQFMbxQlN5dzZYC8aptxR2",
"-KtL2TXGz5JkCd1vA3Z2" : "H5kCOhIQFMbxQlN5dzZYC8aptxR2",
"-KtL2TtWdIFn3I1zvMAD" : "H5kCOhIQFMbxQlN5dzZYC8aptxR2"
},
"userId" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"username" : "Salwa"
},
"-KrdlVlme6Jc6eVbNBTa" : {
"Attend" : 4,
"Category" : "Science & Technology",
"Event date End" : "20/08/2017 10:40 AM",
"Event date Start" : "16/08/2017 10:40 AM",
"EventId" : "-KrdlVlme6Jc6eVbNBTa",
"EventTitle" : "hhhh",
"Fee" : "6666",
"Location" : {
"latitude" : 23.6006718,
"longitude" : 58.55438340000001,
"place name" : "(Great Valley (Alkbir Wadi, Muscat, Oman"
},
"User Email" : "salwa#hotmail.com",
"author" : "abeer",
"commentsId" : "-KrdlVlme6Jc6eVbNBTb",
"description" : "Event Description : ttttt",
"likes" : 5,
"pathToImage" : "https://firebasestorage.googleapis.com/v0/b/event-f39cc.appspot.com/o/events%2FhjAPqucu2jh3sY6v9n9nRM5Fuz73%2F-KrdlVlme6Jc6eVbNBTa.jpg?alt=media&token=4471c063-5432-474e-82b3-030f44ce231f",
"peopleWhoLike" : {
"-Krdlhj9fflCIEguJlPZ" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KrdlhtXEdxuUMRfYJsR" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-Krdlhz1914-GsfDsK21" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KsZDW38ka7dB5NtfrNm" : "Rufida",
"-KsnWCXJNFlZJT5qbh8J" : "FWTfyvXqsXXdI9sy3GihCx8o5a63"
},
"peopleWhoattend" : {
"-Krdlbv9aKWlYNGa1K_d" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-Krdldu17azum7ZH5u-E" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KrdlgBey4dkBLY8FBBK" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"-KtL2V0WEYwRLCLpGvvW" : "H5kCOhIQFMbxQlN5dzZYC8aptxR2"
},
"user name" : "rufida#hotmail.com",
"userId" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"username" : "Salwa"
},
"users" : {
"3IHHOBRaVyR3ldK4hGtcGoY7lox2" : {
"name" : "Rufida",
"uid" : "3IHHOBRaVyR3ldK4hGtcGoY7lox2",
"urlToImage" : "https://firebasestorage.googleapis.com/v0/b/event-f39cc.appspot.com/o/users%2F3IHHOBRaVyR3ldK4hGtcGoY7lox2.jpg?alt=media&token=1c3ee6f2-f688-40b4-b1d6-69f90bf19bb1"
},
"FWTfyvXqsXXdI9sy3GihCx8o5a63" : {
"Email" : "Ola#hotmail.com",
"name" : "Ola",
"uid" : "FWTfyvXqsXXdI9sy3GihCx8o5a63",
"urlToImage" : "https://firebasestorage.googleapis.com/v0/b/event-f39cc.appspot.com/o/users%2FFWTfyvXqsXXdI9sy3GihCx8o5a63.jpg?alt=media&token=289d9b9c-65c1-4ac0-83e4-7f688925f927"
},
"H5kCOhIQFMbxQlN5dzZYC8aptxR2" : {
"Email" : "Salwa#hotmail.com",
"name" : "Salwa",
"uid" : "H5kCOhIQFMbxQlN5dzZYC8aptxR2",
"urlToImage" : "https://firebasestorage.googleapis.com/v0/b/event-f39cc.appspot.com/o/users%2FH5kCOhIQFMbxQlN5dzZYC8aptxR2.jpg?alt=media&token=8f676259-7240-43d2-8735-0896ec9ad090"
},
"hjAPqucu2jh3sY6v9n9nRM5Fuz73" : {
"name" : "abeer",
"uid" : "hjAPqucu2jh3sY6v9n9nRM5Fuz73",
"urlToImage" : "https://firebasestorage.googleapis.com/v0/b/event-f39cc.appspot.com/o/users%2FhjAPqucu2jh3sY6v9n9nRM5Fuz73.jpg?alt=media&token=2c343a4c-c6ad-4dcf-bd0d-10e9a7a635cb"
}
}
}
Attendess collection view to view people who attend
import UIKit
import Firebase
import FirebaseStorage
class AttendeesCollectionViewController: UIViewController , UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
var posts = [Events]()
#IBOutlet weak var CVAttendee: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.barTintColor = UIColor(red: 0, green: 128.0/255.0, blue: 64.0/255.0, alpha: 1.0)
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
// Do any additional setup after loading the view.
fetchEvents()
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height: CGFloat = view.frame.size.height
let width: CGFloat = view.frame.size.width
return CGSize(width: CGFloat(width * 0.95), height: CGFloat(height * 0.75))
}
override func viewDidAppear(_ animated: Bool) {
self.tabBarController?.tabBar.isHidden = false
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.posts.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "UserCell", for: indexPath) as! AttendeeCollectionViewCell
//Creating the cell
cell.lblFirstName.text = self.posts[indexPath.row].FirstName
cell.lblLastName.text = self.posts[indexPath.row].LastName
cell.lblNumberAttendee.text = self.posts[indexPath.row].Attend
if let imagePath = self.posts[indexPath.row].userPic{
cell.imgUser.downloadImage(from: imagePath)
}
else{
cell.imgUser.image = UIImage(named: "abstract-user-flat-4")
}
cell.EventId = self.posts[indexPath.row].EventId
cell.lblEmail.text = self.posts[indexPath.row].Email
cell.lblPhoneNum.text = self.posts[indexPath.row].PhoneNumber
return cell
}
func fetchEvents(){
let dbRef = Database.database().reference()
dbRef.child("Attendee").queryOrdered(byChild: "EventId").observeSingleEvent(of: .value, with: { (snapshot) in
let postData = snapshot.value as! [String: AnyObject]
for(_ ,value ) in postData{
let event = Events()
if
let FirstName = value["UserFirstName"] as? String,
let LastName = value["UserLastName"] as? String,
let Email = value["Email"] as? String,
let PhoneNumber = value["PhoneNumber"] as? String,
let attendingID = value["attendingID"] as? String, // let NumberAttend = value["Event date End"] as? String,
let pathToImage = value["pathToImage"] as? String,
let EventId = value["EventId"] as? String,
let userId = value["userId"] as? String {
event.FirstName = FirstName
event.LastName = LastName
event.Email = Email
event.PhoneNumber = PhoneNumber
event.pathToImage = pathToImage
// event.dateStart = NumberAttend
event.EventId = EventId
event.userId = userId
event.attendingID = attendingID
dbRef.child("users").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snap) in
let users = snap.value as! [String: AnyObject]
for(_ ,userVal) in users {
if let uid = userVal["uid"] as? String{
if uid == userId{
if let img = userVal["urlToImage"] as? String{
event.userPic = img
}
}
}
}
})
dbRef.child("Attendee").observe(.value, with: { (snap) in
// post.commentCount = Int(arc4random_uniform(UInt32(snap.childrenCount)))
let comments = snap.value as! NSDictionary
for key in (comments.allKeys) {
if key as! String == attendingID{
let attendee = comments.value(forKey: attendingID) as! NSDictionary
if let attending = attendee.value(forKey: "Attendees"){
let attending = attending as? NSDictionary
// event.commentCount = messages?.count
}
else{
// event.commentCount = 0
}
self.CVAttendee.reloadData()
}
}
})
self.posts.append(event)
}
}
})
dbRef.removeAllObservers()
}
}
Events class
import UIKit
import Firebase
class Events: NSObject {
var author: String!
var Email: String!
var likes: Int!
var Attend : String!
var commentId: String!
var attendingID : String!
var pathToImage: String!
var userId: String!
var userPic: String!
var EventId: String!
var dateStart: String!
var dateEnd: String!
var desc: String!
var Category: String!
var Fee: String!
var EventTitle: String!
var commentCount: Int!
var SponsorPakage : String!
var locationAddress: NSDictionary!
var peopleWhoLike: [String] = [String]()
var peopleWhoattend: [String] = [String]()
var FirstName: String!
var LastName: String!
var PhoneNumber : String!
var go: goingStatus!
}
Firebase picture
post child firebase database shootscreen
user child firebase shootscreen

Related

How to Display Post Method Requests data in Swiftui Ios Simulator Screen?

This is Doc File Generate in Postman by write method and url "link/services.php".
This is Header File.
#Headers({"Content-Type: application/json"})
 #POST("services.php")
Observable<Division> divisionListApi(#Body HashMap<String, String> map);
map.put("method", "My_List");
After Postman Generation I Got This Given Below.
{"err_code":9,
"message":"My List ",
"list":[
{"ForestDivision":"Yam(T)"},
{"ForestDivision":"Rewar(T)"},
{"ForestDivision":"Ro(T)"},
{"ForestDivision":"Bh(T)"},
{"ForestDivision":"Ka(T) "},
{"ForestDivision":"Ambal(T) "},
{"ForestDivision":"Fari(T)"}]
}
I have made request by taking post mehod, is this the right way to create code in
swiftui.
import Foundation
import Combine
struct File: Decodable, Hashable {
var error_code : Int
var message : String
var list : [lisst]
}
struct lisst: Decodable, Hashable {
var ForestDivision: String
}
class fetchResults : ObservableObject{
#Published var fetchedRes : [lisst]?
func getData(completion: #escaping (File) -> ()){
print("Fetch")
let parameters = "{ I dont Know }"
let postData = parameters.data(using: .utf8)
var request = URLRequest(url: URL(string:
"URl")!,timeoutInterval: Double.infinity)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = postData
let task = URLSession.shared.dataTask(with: request) { (data, _, _) in
let resultList = try! JSONDecoder().decode(File.self, from: data!)
print(" ")
print("ID: \(resultList.error_code)")
print("VOLUME: \(resultList.message)")
print("READINGS: \(String(describing: resultList.list))")
print(" ")
print("SUCCESS: Got data - \(data! )")
DispatchQueue.main.async {
completion(resultList) // << here !!
}
}
task.resume()
}
}
Also How to Write in Swiftui View.
To Make Properly Works in List View.
import SwiftUI
import UIKit
struct DivisionList: View {
#ObservedObject var res = fetchResults()
var body: some View {
NavigationView {
Text("Nothing Here")
List(res.fetchedRes ?? [], id: \.self) { resp in // Error Here
ForEach(res.list, id: \.self) { course in
VStack {
Text(res.for) // Error Here
}
}
}
.navigationBarTitle("Data")
.onAppear(perform: {
self.getData // Error Here
})
}
}
}
struct DivisionList_Previews: PreviewProvider {
static var previews: some View {
DivisionList()
}
}
Create New Swift File Copy this Post Requests.
import Foundation
import Combine
let postUrl = "Your URl"
struct divisionList: Decodable, Identifiable {
let id: Int
let mesg: String
let list: [FDivision]
private enum CodingKeys: String, CodingKey {
case id = "err_code"
case mesg = "message"
case list = "list"
}
}
struct FDivision: Decodable, Hashable {
let forestDivision: String
private enum CodingKeys: String, CodingKey {
case forestDivision = "ForestDivision"
}
init(data:String) {
forestDivision = data
}
}
class viewModal: ObservableObject {
#Published var items = [FDivision]()
func postData() {
guard let serviceUrl = URL(string: postUrl) else { return }
let parameters: [String: Any] = [
"method": "Your Method Name"
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
request.timeoutInterval = 20
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: [])
if let dictionary = json as? [String:Any] {
if let arrList = dictionary["list"] as? [[String:Any]]{
for data in arrList{
let model = FDivision(data: data["ForestDivision"] as! String)
self.items.append(model)
}
}
}
print(json)
} catch {
print(error)
}
}
}.resume()
}
}
Create Now New Swiftui File.
import SwiftUI
import UIKit
struct DivisionList: View {
#ObservedObject var vm = viewModal()
var body: some View {
NavigationView {
VStack {
List(vm.items, id: \.self) { item in
Button(action: {}, label: {
Text(item.forestDivision).foregroundColor(.customGreen)
})
}
}.navigationBarTitle("Data")
.onAppear(perform: {
vm.postData()
})
}
}
}
struct DivisionList_Previews: PreviewProvider {
static var previews: some View {
DivisionList()
}
}

Swiftui how to use MKOverlayRenderer?

I want draw a route on the map.
but struct without using delegate.
struct MapView : UIViewRepresentable {
}
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
}
how can I do?
You need to specify a delegate if you want mapView(_:rendererFor:) to be called:
struct MapView: UIViewRepresentable {
#Binding var route: MKPolyline?
let mapViewDelegate = MapViewDelegate()
func makeUIView(context: Context) -> MKMapView {
MKMapView(frame: .zero)
}
func updateUIView(_ view: MKMapView, context: Context) {
view.delegate = mapViewDelegate // (1) This should be set in makeUIView, but it is getting reset to `nil`
view.translatesAutoresizingMaskIntoConstraints = false // (2) In the absence of this, we get constraints error on rotation; and again, it seems one should do this in makeUIView, but has to be here
addRoute(to: view)
}
}
private extension MapView {
func addRoute(to view: MKMapView) {
if !view.overlays.isEmpty {
view.removeOverlays(view.overlays)
}
guard let route = route else { return }
let mapRect = route.boundingMapRect
view.setVisibleMapRect(mapRect, edgePadding: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10), animated: true)
view.addOverlay(route)
}
}
class MapViewDelegate: NSObject, MKMapViewDelegate {
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.fillColor = UIColor.red.withAlphaComponent(0.5)
renderer.strokeColor = UIColor.red.withAlphaComponent(0.8)
return renderer
}
}
Used like so:
struct ContentView : View {
#State var route: MKPolyline?
var body: some View {
MapView(route: $route)
.onAppear {
self.findCoffee()
}
}
}
private extension ContentView {
func findCoffee() {
let start = CLLocationCoordinate2D(latitude: 37.332693, longitude: -122.03071)
let region = MKCoordinateRegion(center: start, latitudinalMeters: 2000, longitudinalMeters: 2000)
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = "coffee"
request.region = region
MKLocalSearch(request: request).start { response, error in
guard let destination = response?.mapItems.first else { return }
let request = MKDirections.Request()
request.source = MKMapItem(placemark: MKPlacemark(coordinate: start))
request.destination = destination
MKDirections(request: request).calculate { directionsResponse, _ in
self.route = directionsResponse?.routes.first?.polyline
}
}
}
}
Yielding:

Swift 3.0 notification transformable to array or array of dictionaries?

Getting this data back as a notification and want to read it into usable variable types. I got all of them to work but the rewards and aps
%# [AnyHashable("description"): Open 10 common chests., AnyHashable("icon"): localhost:8000//media/achievements/Common%20Chest%20Go- Getter/bomb.jpg, AnyHashable("name"): Common Chest Go-Getter, AnyHashable("gcm.message_id"):1486597426811663%bf6da727bf. 6da727, AnyHashable("rewards"): {"Battle helm":1,"Gems":1000}, AnyHashable("aps"): {
alert = "Achievement Completed";
}]
So how do convert that to a usable variable?
AnyHashable("rewards"): {"Battle helm":1,"Gems":1000}, AnyHashable("aps"): {
alert = "Achievement Completed";
}
The returned item is called userInfo so like...
let rewards = userInfo["rewards"] as! [String:Int]
Doesn't work, any help on this would be greatly appreciated! Again I'm in swift 3.0 so swift 3.0 examples could help.
the notification userInfo is parsed as a Dictionary<String, Any> or [String: Any]
let userInfo: [String: Any] = [
"description": "Open 10 common chests.",
"icon": "localhost:8000//media/achievements/Common%20Chest%20Go- Getter/bomb.jpg",
"name": "Common Chest Go-Getter",
"gcm.message_id": "1486597426811663%bf6da727bf. 6da727",
"rewards": [
"Battle helm": 1,
"Gems":1000
],
"aps": [
"alert": "Achievement Completed"
]
]
if let rewards = userInfo["rewards"] as? [String: Any] {
if let battle = rewards["Battle helm"] as? Int {
print(battle) // 1
}
if let gems = rewards["Gems"] as? Int {
print(gems) // 1000
}
}
if let aps = userInfo["aps"] as? [String: Any] {
if let alert = aps["alert"] as? String {
print(alert) // Achievement Completed
}
}
Looks like you are confused with this:
let arrayOfStrings = [String]()
let dictionary = [String: Any]()
let arrayOfDictionaries = [[String:Any]]()

Swift 3 , CollectionView, Alamofire 4 : finding nil while unwrapping a value

Here is my JSON response
{
"category_list" : [
{
"category_imag" : "http:\/\/xxx\/wp-content\/uploads\/2016\/10\/img-thing.jpg",
"category_name" : "category 1",
"category_description" : "dsadsadas",
"category_id" : 6
},
{
"category_imag" : "http:\/\/xxx\/wp-content\/uploads\/2016\/09\/7075hp_2_2.jpg",
"category_name" : "category 2",
"category_description" : "dasdadasdas",
"category_id" : 12
}
]
}
items are***********************************************
{
"category_imag" : "http:\/\/xxx\/wp- content\/uploads\/2016\/10\/img-thing.jpg",
"category_description" : "dsadsadas",
"category_name" : "category 1",
"category_id" : 6
}
{
"category_imag" : "http:\/\/xxx\/wp- content\/uploads\/2016\/09\/7075hp_2_2.jpg",
"category_description" : "dasdadasdas",
"category_name" : "category 2",
"category_id" : 12
}
items number***********************************************
2
fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)
here is the function I am using to fetch JSON using Alamofire & SwiftyJSON
func getJSON(){
let getEndPoint: String = "http://xxx/api/category_list/"
Alamofire.request(getEndPoint)
.responseJSON { response in
guard response.result.error == nil else {
// got an error in getting the data, need to handle it
print("error calling GET")
print(response.result.error!)
return
}
if let value = response.result.value {
let json = JSON(value)
print(json)
// print(json["main_content"].array)
let categoryList = json["category_list"].arrayValue
for items in categoryList {
//self.productList += [HomeFeedJSON(items:items )]
self.getCategoryList.append(CategoryList(items: items))
print(items)
}
print("items are***********************************************")
print(self.getCategoryList.count)
DispatchQueue.main.async {
self.afData = 1
self.collectionView?.reloadData()
}
}
}
}
and here is the model class I am using for assigning the values fetched from JSON
import Foundation
import SwiftyJSON
class CategoryList {
var category_name: String?
var category_imag: URL?
var category_description: String?
init(items: JSON){
self.category_name = items["category_name"].stringValue
self.category_imag = items["category_imag"].URL
self.category_description = items["category_description"].stringValue
}
}
I don't want to bother people but I have tried all possible way I could, its showing nil on my collectionViewCell . in numberOfItemsInSection I am getting intended result but at cellForItemAt indexPath it shows nil value and crashes. Here is my cellForItemAt indexPath
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CatagoryShopCell", for: indexPath) as! CatagoryShopCell
if afData == 1 {
let myCategory = self.getCategoryList[indexPath.row]
cell.catagoryName.text = myCategory.category_name
cell.catagoryDesc.text = myCategory.category_description
let categoryImg = myCategory.category_imag
SDWebImageManager.shared().downloadImage(with: categoryImg, options: [], progress: nil) { downloadedImage, error, cacheType, isDownloaded, url in
cell.catagoryPicture.image = downloadedImage
}
}
return cell
}
I have used the same function/model class in a tableView in it works just fine, but I can't sort it out how its not finding value in my model class here at collectionView . Please any kind person help. Thank you in advance.

Swift / How to parse json from java spring code

I want to parse json from java spring code (Xcode 7.3 / Swift). I tried almost every solution from all sites.
When I register it gives the following error message at the console:
Response = Optional(<NSHTTPURLResponse: 0x7a7607e0> { URL: http://www.____.com/saveRegistrationJson.htm } { status code: 405, headers {
Allow = GET;
Connection = "Keep-Alive";
"Content-Length" = 1089;
"Content-Type" = "text/html;charset=utf-8";
Date = "Wed, 04 May 2016 12:21:34 GMT";
"Keep-Alive" = "timeout=15, max=100";
Server = "Apache-Coyote/1.1";
} })
before json
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
This is my Code:
import UIKit
class RegistrationViewController: UIViewController {
#IBOutlet weak var userfnametextfield: UITextField!
#IBOutlet weak var userlnametextfield: UITextField!
#IBOutlet weak var useremailtextfield: UITextField!
#IBOutlet weak var userpwdtextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func RegisterbtnTapped(sender: AnyObject) {
let fname = userfnametextfield.text
let lname = userlnametextfield.text
let Email = useremailtextfield.text
let pwd = userpwdtextfield.text
//check empty fields
if(fname!.isEmpty || lname!.isEmpty || Email!.isEmpty || pwd!.isEmpty )
{
DisplayMyAlertMessage("All Fields are required")
return
}
//store data
NSUserDefaults.standardUserDefaults().setObject(fname, forKey: "fname")
NSUserDefaults.standardUserDefaults().setObject(lname, forKey: "lname")
NSUserDefaults.standardUserDefaults().setObject(Email, forKey: "Email")
NSUserDefaults.standardUserDefaults().setObject(pwd, forKey: "password")
NSUserDefaults.standardUserDefaults().synchronize()
//send user data to server side
let myurl = NSURL(string: "http://www.____.com/saveRegistrationJson.htm")
let request = NSMutableURLRequest(URL: myurl!)
request.HTTPMethod = "POST"
let poststring = "fname\(fname!)&lname\(lname!)&email\(Email!)&password\(pwd!)"
request.HTTPBody = poststring.dataUsingEncoding(NSUTF8StringEncoding)
//request.HTTPBody = postData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data,response, error in
if error != nil{
print("Error\(error)")
return
}
print("Response = \(response)")
do{
var err : NSError?
print("before json")
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
print(json)
print("After json")
//print("demo : \(response?.description)")
guard let parseJSON = json else{
print("parsing json here:")
return
}
// guard let value = NSString(data: data!, encoding: NSUTF8StringEncoding) else{
// print("parsed")
// return
//}
//print("FirstName\(value)")
var requestValue = parseJSON[" "] as? String
print("result:\(requestValue)")
var isUserRegistered:Bool = false
if(requestValue=="Success") { isUserRegistered = true}
var messageToDisplay:String = parseJSON["Success"] as! String
if(!isUserRegistered){
messageToDisplay = parseJSON[" "] as! String
}
dispatch_async(dispatch_get_main_queue(), {
let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
let onAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (ACTION) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
myAlert.addAction(onAction)
self.presentViewController(myAlert, animated: true, completion: nil)
})
}
catch let error as NSError
{
print(error)
}
}
task.resume()
Help is very appreciated.