Hello I am using the linked in SDK to log into my app.
The API returns a json string which i have converted to a dictionary object.
Using the line below I can successfully retrieve some of the values.
let firstName : NSString? = dict?["firstName"] as? NSString
How would I retrieve the company name and the job title?
["publicProfileUrl": https://www.linkedin.com/in/joebloggs, "formattedName": Joe Bloggs, "id": Zazobgtf1Q, "pictureUrls": {
"_total" = 1;
values = (
"https://media.licdn.com/mpr/mprx/0_xBXVf6v56zJf42DuUQJy70N69gfspmi8VYJMYZq_Q6X8SCm_a-4jUmz6FF4wOai_xjJMpPN_qiNQ7xaiUpvv4jq5_iN67xx8apv4S6HL9JLf7HadaZ5JIuNzlJ"
);
}, "pictureUrl": https://media.licdn.com/mpr/mprx/0_OzOPtLSS9GH8gFDYUA6-xtfSKPkgY5YmNkEPBAGSc5ypRvS_AzXjVcuSNssssXO_qkE1Mi_DxXcyZT2mBQR7sAa3VXcjZTdGlQRKlrR2ALGltB-YjcSOAkzjslDDATY14Lxx9mjGA2G, "lastName": Bloggs, "emailAddress": joe#gmail.com, "positions": {
"_total" = 1;
values = (
{
company = {
id = 9433004;
industry = "Marketing & Advertising";
name = "Company Name";
size = "2-10";
type = "Privately Held";
};
id = 865817330;
isCurrent = 1;
location = {
country = {
code = gb;
name = "United Kingdom";
};
name = "Leeds, United Kingdom";
};
startDate = {
month = 9;
year = 2016;
};
title = "Staff";
}
);
}, "firstName": Joe]
Here is the code I am using for the linkedIn login:
func linkedInLogin(){
LISDKSessionManager.createSession(withAuth: [LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION], state: nil, showGoToAppStoreDialog: true, successBlock: { (returnState) -> Void in
print("success called!")
let session = LISDKSessionManager.sharedInstance().session
//let url = "https://api.linkedin.com/v1/people/~"
let url = "https://api.linkedin.com/v1/people/~:(id,summary,positions,email-address,first-name,last-name,public-profile-url,formatted-name,picture-url,picture-urls::(original))?format=json"
if LISDKSessionManager.hasValidSession() {
LISDKAPIHelper.sharedInstance().getRequest(url, success: { (response) -> Void in
// print(response!.data!)
let str = response!.data!
let dict = self.convertToDictionary(text: str)
print(dict!)
let firstName : NSString? = dict?["firstName"] as? NSString
let lastName : NSString? = dict?["lastName"] as? NSString
let email : NSString? = dict?["emailAddress"] as? NSString
let userName : NSString? = dict?["formattedName"] as? NSString
let linkedInID : NSString? = dict?["id"] as? NSString
let link : NSString? = dict?["publicProfileUrl"] as? NSString
let liid : NSString? = dict?["id"] as? NSString
let picurl : NSString? = dict?["pictureUrl"] as? NSString
// let summary : NSString? = dict?["summary"] as? NSString
let positions : NSString? = dict?["positions"] as? NSString
}, error: { (error) -> Void in
print(error!)
})
}
}) { (error) -> Void in
print("Error: \(error)")
}
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
Related
I have a Channel Method in my Flutter project which takes a String (url), downloads an image and presents it as part of a new contact.
However, the image won't be displayed for most urls.
This is the code I use to get the image and add to the new contact, before displaying it in a CNContactViewController.
let urlString : String = (arguments["imgUrl"] as? String)!
let url = URL(string: urlString)
let data = try? Data(contentsOf: url!)
newContact.imageData = data
I have tried encoding the url and casting it as an NSString with no luck.
Interesting, if I hard code the url in like below, it works. So what is happening between sending it from my Dart source code, over to Swift?
(URL modified to conceal contents, real URL returns image)
let url = URL(string: "https://23ee7ca4ch9430946b76-4f3bba1a032272305d39a357e474f3b2.ssl.cf1.rackcdn.com/talent/81843293_1556369106.jpeg")
let data = try? Data(contentsOf: url!)
newContact.imageData = data
Update:
Here is the full code...
Dart:
static const platform = const MethodChannel('contacts');
static Future<String> addSystemContact({
String firstName,
String lastName,
String jobTitle,
String company,
String phone,
String email,
String city,
String country,
String profile,
String imgUrl,
}) async {
try {
var result = await platform.invokeMethod(
'addSystemContact',
{
'firstName' : firstName != null && firstName.isNotEmpty ? firstName : "",
'lastName' : lastName != null && lastName.isNotEmpty ? lastName : "",
'jobTitle' : jobTitle,
'company' : company,
'phone' : phone,
'email' : email,
'city' : city,
'country' : country,
'profile' : profile,
'imgUrl': imgUrl,
},
);
return result;
} on PlatformException catch (e) {
return null;
}
}
Swift:
let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
let contactChannel = FlutterMethodChannel(name: "contacts", binaryMessenger: controller)
contactChannel.setMethodCallHandler({(call: FlutterMethodCall, result: #escaping FlutterResult) -> Void in
//ADD SYSTEM CONTACT
//
if (call.method == "addSystemContact") {
let arguments : Dictionary = call.arguments as! Dictionary<String,Any>
guard let firstName : String = arguments["firstName"] as? String else { return result(false); }
guard let lastName : String = arguments["lastName"] as? String else { return result(false); }
//create contact
let newContact = CNMutableContact()
newContact.contactType = CNContactType.person
newContact.givenName = firstName
newContact.familyName = lastName
if let jobTitle : String = arguments["jobTitle"] as? String {
newContact.jobTitle = jobTitle
}
if let company : String = arguments["company"] as? String {
newContact.organizationName = company
}
if let phone : String = arguments["phone"] as? String {
newContact.phoneNumbers = [CNLabeledValue(
label:CNLabelPhoneNumberMain,
value:CNPhoneNumber(stringValue:phone))]
}
if let email : NSString = arguments["email"] as? NSString {
newContact.emailAddresses = [CNLabeledValue(label:CNLabelWork, value:email)]
}
let address = CNMutablePostalAddress()
if let city : String = arguments["city"] as? String {
address.city = city
}
if let country : String = arguments["country"] as? String {
address.country = country
}
newContact.postalAddresses = [CNLabeledValue(label:CNLabelWork, value:address)]
if let profile : String = arguments["profile"] as? String {
newContact.socialProfiles = [CNLabeledValue(label:
CNSocialProfileServiceLinkedIn, value: CNSocialProfile.init(urlString: profile, username: nil, userIdentifier: nil, service: nil))]
}
// Offending code...
//
let urlString : String = (arguments["imgUrl"] as? String)!
let url = URL(string: urlString)
let data = try? Data(contentsOf: url!)
newContact.imageData = data
//
//
//presents nav controller with CNContactViewController
self.displayConactViewController(newContact: newContact, result: result)
}
})
You seem to have a mix of methodologies. Are you passing a single string as the argument, or a map? Unfortunately you don't show the Dart end.
Here are some working examples, adapted from a working plugin.
Single String
Dart end
static void ping(String pong) {
_channel.invokeMethod('ping', pong);
}
Swift end - call.arguments is a String
case "ping":
NSLog("ping")
if let pong = call.arguments as! String {
// do something
} else {
NSLog("ping - Invalid Args")
}
break
String as map member
Dart end
static void foo(String bar, String baz) {
_channel.invokeMethod('foo', <String, dynamic>{
'bar': bar,
'baz': baz,
});
}
Swift end - call.arguments is a Dictionary
case "foo":
NSLog("foo")
if let args = call.arguments as? Dictionary<String, Any>, let bar = args["bar"] as! String {
// do something with bar and/or args["baz"] as! String
} else {
NSLog("foo - Args is not a Dictionary")
}
break
How can I clear the shared dictionary on logout in which I am saving login response?
Here is the code I am doing on getting status 1.
if(status == 1)
{
DispatchQueue.main.async {
GAReusableClass.sharedInstance.hideActivityIndicator()
UserDefaults.standard.set(self.DataDict, forKey:MaindataKey)
let Dict = self.mainDict[KData] as! [String: AnyObject]
print("self.DataDict", self.DataDict)
let User_ID = Dict[KUuid]as! String
print(User_ID)
let HMACSECRETKEY = self.deviceToken + "+" + User_ID
kHMACKey = HMACSECRETKEY
let cipher:String = CryptoHelper.encrypt(input:HMACSECRETKEY)!;
print(HMACSECRETKEY)
UserDefaults.standard.setValue(cipher, forKey:HmacKey)
UserDefaults.standard.set(true, forKey: "isLogin")
GAloginUserInfo.shared.saveUserInfo(dict: Dict )
let tabar = self.storyboard?.instantiateViewController(withIdentifier: "GAtHomeTabbarViewController") as! GAtHomeTabbarViewController
self.navigationController?.pushViewController(tabar, animated: true)
}
Here is the shared dictionary which I am using to save the values of login response.
import UIKit
import Firebase
class GAloginUserInfo: NSObject {
var loginUserMobileNo : String?
var loginUserId : String?
var loginUserUuid : String?
var loginUserCountry : String?
var loginUserCountryCode : String?
var loginUserEmail : String?
var loginUserlatitude : String?
var loginUserLongitude : String?
var loginUserName : String?
var loginUserQrcode : String?
var loginUserProfilePic : String?
var isverify : String?
var loginPassword : String?
var dateOfBirth: String?
var earnedPoints:String?
var loginUserGender:String?
var loginUserFollowers:Int = 0
static let shared = GAloginUserInfo()
func saveUserInfo (dict : [String : AnyObject?] ) {
if let loginUserMobileNo = dict["mobile"] as? String {
self.loginUserMobileNo = loginUserMobileNo
}
if let loginUserId = dict["id"] as? String {
self.loginUserId = loginUserId
}
if let loginUserUuid = dict["uuid"] as? String {
self.loginUserUuid = loginUserUuid
print(loginUserUuid)
}
if let loginUserCountry = dict["country"] as? String {
self.loginUserCountry = loginUserCountry
}
if let loginUserCountryCode = dict["country_code"] as? String {
self.loginUserCountryCode = loginUserCountryCode
}
if let loginUserEmail = dict["email"] as? String {
self.loginUserEmail = loginUserEmail
}
if let loginUserProfilePic = dict["profile_pic"] as? String {
self.loginUserProfilePic = loginUserProfilePic
}
if let loginUserLongitude = dict["logitude"] as? String {
self.loginUserLongitude = loginUserLongitude
}
if let loginUserName = dict["name"] as? String {
self.loginUserName = loginUserName
}
if let loginUserQrcode = dict["qr_code"] as? String {
self.loginUserQrcode = loginUserQrcode
}
if let Password = dict["password"] as? String{
self.loginPassword = Password
}
if let dateOfBirth = dict["dob"] as? String{
self.dateOfBirth = dateOfBirth
}
if let earnedPoints = dict["points"] as? String{
let myDouble = Double(earnedPoints)
let doubleStr = String(format: "%.2f", myDouble!)
self.earnedPoints = doubleStr
}
if let loginUserGender = dict["gender"] as? String{
self.loginUserGender = loginUserGender
}
if let loginUserFollowers = dict["followersCount"] as? Int{
self.loginUserFollowers = loginUserFollowers
}
}
}
Actually, the problem is when I log out and log in again with some other user it still shows some values of the previous user. I am clearing the userdefaults on the logout function. but I don't know how to clear this type of shared dictionary.
Use removeObject(forKey:)
to remove the values stored from user defaults in Logout method
UserDefaults.standard.removeObject(forKey: MaindataKey)
UserDefaults.standard.removeObject(forKey: HmacKey)
UserDefaults.standard.set(false, forKey: "isLogin")
Create a method to remove the values from the singleton class like this
extension GAloginUserInfo {
func removeUserInfo() {
self.loginUserMobileNo = nil
self.loginUserId = nil
self.loginUserUuid = nil
self.loginUserCountry = nil
self.loginUserCountryCode = nil
self.loginUserEmail = nil
self.loginUserlatitude = nil
self.loginUserLongitude = nil
self.loginUserName = nil
self.loginUserQrcode = nil
self.loginUserProfilePic = nil
self.isverify = nil
self.loginPassword = nil
self.dateOfBirth = nil
self.earnedPoints = nil
self.loginUserGender = nil
self.loginUserFollowers = 0
}
}
and call this method in logout
GAloginUserInfo.shared.removeUserInfo()
this is my respone
{
activeFromDate = "01/01/2017";
terminateDate = “02/05/2019”;
}
{
activeFromDate = "01/01/2013";
terminateDate = "<null>";
}
{
activeFromDate = "01/01/2017";
terminateDate = "02/05/2018";
}
{
activeFromDate = "07/01/2012";
terminateDate = "<null>";
}
{
activeFromDate = "01/01/2017";
terminateDate = "02/05/2019";
}
this is my code
let answerArray = NSMutableArray()
for i in 0..<arr.count
{
let dict = Dictionary[i] as! NSDictionary
let name1 = dict.value(forKey:"terminateDate") as! String
if(name1 == "")
{
print (answerArray.add(dict))
}
}
this is my nsdictionary response
how to get array count if terminatedDate is null and terminatedDate is greater than today date?
I have created a sample to read json file placed in your project. and have integrated the code as per your requirement.
Json File
{"Status":"success","Data":[
{"activeFromDate":"01/01/2017","terminateDate":"02/05/2019"},
{"activeFromDate":"01/01/2013","terminateDate":null},
{"activeFromDate":"01/01/2017","terminateDate":"02/05/2018"},
{"activeFromDate":"07/01/2012","terminateDate":null},
{"activeFromDate":"01/01/2017","terminateDate":"02/05/2016"},
{"activeFromDate":"01/01/2017","terminateDate":"02/05/2019"}
]
}
In your View Controller
import UIKit
class HomeViewController: UIViewController {
let answerArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
jsonParsingFromFile()
}
func jsonParsingFromFile()
{
let path: NSString = Bundle.main.path(forResource: "tjw", ofType: "json")! as NSString
let data : NSData = try! NSData(contentsOfFile: path as String, options: NSData.ReadingOptions.dataReadingMapped)
self.startParsing(data: data)
}
func startParsing(data :NSData)
{
let dict: NSDictionary!=(try! JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions.mutableContainers)) as? NSDictionary
//print(dict)
guard let dataArr:NSArray = dict.value(forKey: "Data") as? NSArray else {
return
}
print(dataArr.count)
for i in 0..<dataArr.count{
guard let currentDict:NSDictionary = dataArr[i] as? NSDictionary else {
return
}
let activeFromDateStr:String = currentDict.value(forKey: "activeFromDate") as? String ?? ""
let terminateDateStr:String = currentDict.value(forKey: "terminateDate") as? String ?? ""
print(activeFromDateStr, terminateDateStr)
if terminateDateStr != ""{
let date2 = convertToDate(dateStr: terminateDateStr)
let today = Date()
if date2>today{
answerArray.add(currentDict)
}
}else{
answerArray.add(currentDict)
}
}
print(answerArray)
}
func convertToDate(dateStr:String)->Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
dateFormatter.locale = Locale(identifier: "en_IN")
let date = dateFormatter.date(from: dateStr)!
return date
}
}
people in my app sometimes needs to update the status of something. Now can you choose of 2 things: The so called "Rollerbank" is still there or the "Rollerbank" is removed. The users can create a data ref. The id that will be created by childbyAutoID. Now is my question how to get the right child and update some childs with a value. My post:
class Post {
let ref: DatabaseReference!
var TypeControle: String = ""
var Stad: String = ""
var Tijd: String = ""
var TijdControle: String = ""
var TijdControleniet: String = ""
var Latitude: String = ""
var Longitude: String = ""
var Extrainformatie: String = ""
var Staater: String = ""
var Staaternietmeer: String = ""
init(TypeControle: String) {
self.TypeControle = TypeControle
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Stad: String){
self.Stad = Stad
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Tijd: String) {
self.Tijd = Tijd
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Latitude: String) {
self.Latitude = Latitude
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Longitude: String) {
self.Longitude = Longitude
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Extrainformatie: String) {
self.Extrainformatie = Extrainformatie
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(Staater: String) {
self.Staater = Staater
ref = Database.database().reference().child("Rollerbanken").child("Controletest").childByAutoId()
}
init(Staaternietmeer: String) {
self.Staaternietmeer = Staaternietmeer
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(TijdControle: String) {
self.TijdControle = TijdControle
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(TijdControleniet: String) {
self.TijdControleniet = TijdControleniet
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init() {
ref = Database.database().reference().child("Rollerbanken").childByAutoId()
}
init(snapshot: DataSnapshot)
{
ref = snapshot.ref
if let value = snapshot.value as? [String : Any] {
TypeControle = value["TypeControle"] as! String
Stad = value["Stad"] as! String
Tijd = value["Tijd"] as! String
Latitude = value["Latitude"] as! String
Longitude = value["Longitude"] as! String
Extrainformatie = value["Extrainformatie"] as! String
Staater = value["Staater"] as! String
Staaternietmeer = value["Staaternietmeer"] as! String
TijdControle = value["TijdControle"] as! String
TijdControleniet = value["TijdControleniet"] as! String
}
}
func save() {
ref.setValue(toDictionary())
}
func toDictionary() -> [String : Any]
{
return [
"TypeControle" : TypeControle,
"Stad" : Stad,
"Tijd" : Tijd,
"Latitude" : Latitude,
"Longitude" : Longitude,
"Extrainformatie" : Extrainformatie,
"Staater" : Staater,
"Staaternietmeer" : Staaternietmeer,
"TijdControle" : TijdControle,
"TijdControleniet" : TijdControleniet
]
}
}
Data for the TableViewCell:
class ControleTableViewCell: UITableViewCell {
#IBOutlet weak var storyControle: UILabel!
#IBOutlet weak var storyTijd: UILabel!
var post: Post! {
didSet {
storyControle.text = "\(post.Staaternietmeer)"
storyTijd.text = "\(post.TijdControleniet)"
storyControle.text = "\(post.Staater)"
storyTijd.text = "\(post.TijdControle)"
}
}
How my update button looks like:
#IBAction func Update(_ sender: Any) {
let alertController1 = UIAlertController(title: "Update melden" , message: "De rollerbank", preferredStyle: .alert)
// Create the actions
let RollerbankAction1 = UIAlertAction(title: "Staat er nog steeds", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("Ja Pressed")
self.newStory.Staater = self.Staater
self.newStory.TijdControle = self.TijdControle
self.newStory.save()
}
let cancelAction1 = UIAlertAction(title: "Staat er niet meer", style: UIAlertActionStyle.cancel) {
UIAlertAction in
NSLog("Cancel Pressed")
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let Tijd = "\(hour) : \(minutes)"
self.newStory.Staaternietmeer = self.Staaternietmeer
self.newStory.TijdControleniet = Tijd
self.newStory.save()
}
alertController1.addAction(RollerbankAction1)
alertController1.addAction(cancelAction1)
self.present(alertController1, animated: true, completion: nil)
}
This is the Structure that i use. If i run all this code, the new data will go in a other childbyAutoID and thats not what i want. It just needs to update/setvalue in the cleare space named "Staaternietmeer" and "TijdControleniet". Can anybody help me with that?
You would then need to store the Push ID somewhere so that you can reuse it later.
To generate a unique Push ID you would use :
Database.database().reference().childByAutoId()
And to store it somewhere :
let postKey = Database.database().reference().childByAutoId().key
And then, say you need a method to share a post for example, and want to add this post to multiple nodes, that's how it may look like :
func sharePost(_ postContent: String, completion: #escaping (Bool) -> ()) {
guard let currentUserId = Auth.auth().currentUser?.uid else {
completion(false)
return
}
let postKey = Database.database().reference().childByAutoId().key
let postData: [String: Any] = [ "content": "blabla",
"author": currentUserId ]
let childUpdates: [String: Any] = ["users/\(currentUserId)/posts/\(postKey)": true,
"posts/\(postKey)": postData ]
Database.database().reference().updateChildValues(childUpdates, withCompletionBlock: { (error, ref) in
guard error == nil else {
completion(false)
return
}
completion(true)
})
}
Now to access the unique Push ID later on, you would use :
Database.database().reference().observe(.childAdded, with: { (snapshot) in
// Here you get the Push ID back :
let postKey = snapshot.key
// And others things that you need :
guard let author = snapshot.childSnapshot(forPath: "author").value as? String else { return }
guard let content = snapshot.childSnapshot(forPath: "content").value as? String else { return }
// Here you store your object (Post for example) in an array, and as you can see you initialize your object using the data you got from the snapshot, including the Push ID (`postKey`) :
posts.append(Post(id: postKey, content: content, author: author))
})
I am using the linkedIn SDK in my app to create a linkedIn login.
I am attempting to get the company name from the API but keep getting nil on the line:
print("Company: (companyString!)")
The dict is as follows:
["publicProfileUrl": https://www.linkedin.com/in/joebloggs, "formattedName": Joe Bloggs, "id": Zazobgtf1Q, "pictureUrls": {
"_total" = 1;
values = (
"https://media.licdn.com/mpr/mprx/0_xBXVf6v56zJf42DuUQJy70N69gfspmi8VYJMYZq_Q6X8SCm_a-4jUmz6FF4wOai_xjJMpPN_qiNQ7xaiUpvv4jq5_iN67xx8apv4S6HL9JLf7HadaZ5JIuNzlJ"
);
}, "pictureUrl": https://media.licdn.com/mpr/mprx/0_OzOPtLSS9GH8gFDYUA6-xtfSKPkgY5YmNkEPBAGSc5ypRvS_AzXjVcuSNssssXO_qkE1Mi_DxXcyZT2mBQR7sAa3VXcjZTdGlQRKlrR2ALGltB-YjcSOAkzjslDDATY14Lxx9mjGA2G, "lastName": Bloggs, "emailAddress": joe#gmail.com, "positions": {
"_total" = 1;
values = (
{
company = {
id = 9433004;
industry = "Marketing & Advertising";
name = "Company Name";
size = "2-10";
type = "Privately Held";
};
id = 865817330;
isCurrent = 1;
location = {
country = {
code = gb;
name = "United Kingdom";
};
name = "Leeds, United Kingdom";
};
startDate = {
month = 9;
year = 2016;
};
title = "Staff";
}
);
}, "firstName": Joe]
I am using the code below:
func linkedInLogin(){
LISDKSessionManager.createSession(withAuth: [LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION], state: nil, showGoToAppStoreDialog: true, successBlock: { (returnState) -> Void in
print("success called!")
let session = LISDKSessionManager.sharedInstance().session
//let url = "https://api.linkedin.com/v1/people/~"
let url = "https://api.linkedin.com/v1/people/~:(id,summary,positions,email-address,first-name,last-name,public-profile-url,formatted-name,picture-url,picture-urls::(original))?format=json"
if LISDKSessionManager.hasValidSession() {
LISDKAPIHelper.sharedInstance().getRequest(url, success: { (response) -> Void in
// print(response!.data!)
let str = response!.data!
let dict = self.convertToDictionary(text: str)
print(dict!)
let firstName : String? = dict!["firstName"] as! String?
let lastName : NSString? = dict?["lastName"] as? NSString
let email : NSString? = dict?["emailAddress"] as? NSString
let userName : NSString? = dict?["formattedName"] as? NSString
let linkedInID : NSString? = dict?["id"] as? NSString
let link : NSString? = dict?["publicProfileUrl"] as? NSString
let liid : NSString? = dict?["id"] as? NSString
let picurl : NSString? = dict?["pictureUrl"] as? NSString
// let summary : NSString? = dict?["summary"] as? NSString
let positions : NSString? = dict?["positions"] as? NSString
var companyString:String!
// let type = (self.data[indexPath.row] as? [String : String])?["Type"]
if let company = (dict?["company"] as? [String : String])?["name"]{
companyString = company
}
print("FIRSTNAME: \(firstName!)")
print("LASTNAME: \(lastName!)")
if email != nil {print("email: \(email!)")}
print("userName: \(userName!)")
print("linkedinid: \(linkedInID!)")
print("Link: \(link!)")
print("Liid: \(liid!)")
print("pic url: \(picurl!)")
// print("summary: \(summary!)")
print("positions: \(positions!)")
print("Company: \(companyString!)")
}, error: { (error) -> Void in
print(error!)
})
}
}) { (error) -> Void in
print("Error: \(error)")
}
}
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
The value for company is [String:Any] because id is Int
if let dict = self.convertToDictionary(text: str) {
...
if let company = dict["company"] as? [String : Any],
let companyName = company["name"] as? String {
print(companyName)
}
...
}
Side notes:
Don't annotate types the compiler can infer.
Don't use NSString in Swift.
There are too many exclamation and question marks. Use optional bindings to get safely unwrapped non-optional types.