Got Empty array from accountsWithAccountType: in IPhone - ios6

I got belo lines of code to execute -
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:
ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType options:nil
completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
NSArray *arrayOfAccounts = [account
accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject];
NSDictionary *message = #{#"status": #"My First Twitter post from iOS6"};
NSURL *requestURL = [NSURL
URLWithString:#"http://api.twitter.com/1/statuses/update.json"];
SLRequest *postRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:requestURL parameters:message];
postRequest.account = twitterAccount;
[postRequest performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse, NSError *error)
{
NSLog(#"Twitter HTTP response: %i", [urlResponse
statusCode]);
}];
}
}
}];
I got an empty array while I'm passing acccount type object to accountsWithAccountType: method. While I have started to debug this code I got below description of account type object.
Printing description of accountType:
identifier: com.apple.twitter
description: Twitter
objectID:
x-coredata://C4E0FB79-AAAF-4E87-92AD-C80137717067/AccountType/p25
supportsAuthentication YES
supportsMultipleAccounts YES
supportedDataclasses (null)
syncableDataclasses (null)
is there something missed by me?
please help me to sort out this.
thanks in advance.

Related

Problem converting JSON to Array with Swift

I try to convert a JSON to an Array but I face some issue and do not know how to sort it out.
I use Swift 5 and Xcode 12.2.
Here is the JSON from my PHP query:
[
{
Crewcode = AAA;
Phone = 5553216789;
Firstname = Philip;
Lastname = MILLER;
email = "pmiller#xxx.com";
},
{
Crewcode = BBB;
Phone = 5557861243;
Firstname = Andrew;
Lastname = DEAN;
email = "adean#xxx.com";
}
]
And here is my Swift code :
let url: URL = URL(string: "https://xxx.php")!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed to download data")
}
else {
print("Data downloaded")
do {
if let jsondata = (try? JSONSerialization.jsonObject(with: data!, options: [])) {
print(jsondata)
struct Crew: Decodable {
var Code: String
var Phone: String
var Firstname: String
var Lastname: String
var email: String
}
let decoder = JSONDecoder()
do {
let people = try decoder.decode([Crew].self, from: jsondata as! Data)
print(people)
}
catch {
print(error)
}
}
}
}
}
task.resume()
When I run my code I get the following error:
Could not cast value of type '__NSArrayI' (0x7fff86b930b0) to 'NSData' (0x7fff86b911e8).
2020-12-09 14:52:48.988468+0100 FTL[57659:3019805] Could not cast value of type '__NSArrayI' (0x7fff86b930b0) to 'NSData' (0x7fff86b911e8).
Could not cast value of type '__NSArrayI' (0x7fff86b930b0) to 'NSData' (0x7fff86b911e8).
Should you have any idea to get it right, I thank you in advance for your assistance on this !
You are deserializing the JSON twice by mixing up JSONSerialization and JSONDecoder.
Delete the first one
if let jsondata = (try? JSONSerialization.jsonObject(with: data!, options: [])) {
– By the way the JSON in the question is neither fish nor fowl, neither JSON nor an NS.. collection type dump –
and replace
let people = try decoder.decode([Crew].self, from: jsondata as! Data)
with
let people = try decoder.decode([Crew].self, from: data!)
and the struct member names must match the keys otherwise you have to add CodingKeys

Type 'String' does not conform to protocol 'NSCopying' - Array swift json Error

sorry in advance for my bad english.
I have a problem with my Swiftcode, i'm new in Swift so maybe you can help me :)
Here is my Code.
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if(error != nil)
{
println("error\(error)")
return;
}
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
if let parseJSON = json
{
var resultValue:String = parseJSON["message"] as String!;
println("result: \(resultValue)")
self.LabelFalscheEingabe.text = "\(resultValue)";
if(resultValue == "Success")
{
var Projects:Array = parseJSON["projects"] as Array!; // here is the Error
}
}
task.resume()
}
'projects' is a variable from type Array on the server, so i want to get it as Array from the server, but if I try this i get the following error.
Error: "Type 'String' does not conform to protocol 'NSCopying'".
Thanks in advance :)
YourProjects array can't be declared like that, Swift has to know the type of the objects in the array.
If you don't know the type, then make it an array of AnyObject:
if let Projects = parseJSON["projects"] as? [AnyObject] {
// do something with Projects
}
If you know it's an array of Strings, for example:
if let Projects = parseJSON["projects"] as? [String] {
// do something with Projects
}
An array of Integers:
if let Projects = parseJSON["projects"] as? [Int] {
// do something with Projects
}
An array of dictionaries made from JSON:
if let Projects = parseJSON["projects"] as? [[String:AnyObject]] {
// do something with Projects
}
Etc.

Error while retrieving Parse data into an array

var titles = [String]()
var descriptions = [String]()
func retrieveData () {
var query = PFQuery(className: "Main")
// get the actual data
query.getFirstObjectInBackgroundWithBlock {
(object: PFObject?, error: NSError?) -> Void in
if error != nil || object == nil {
println("Error retrieving data")
} else {
self.titles.append(object["Labels"] as! String) // ERROR!
self.descriptions.append(object["desc1"] as! String) // ERROR!
}
}
}
I have 2 arrays and I want to retrieve data from Parse and add it to those arrays, but I get this error:
Cannot invoke 'append' with an argument list of type '(String)'
What am I doing wrong ?
Edit: this is what I get when I println(object) :
Optional(<Main: 0x7fc24b84e410, objectId: jy7LrEOMk0, localId: (null)> {
Labels = labels;
desc1 = desc1;
desc2 = desc2;
desc3 = desc3;
desc4 = desc4;
desc5 = desc5;
})
Message from debugger: got unexpected response to k packet: OK
After spending several hours trying & searching, this is the correct answer:
self.titles.append(object?.objectForKey("Labels") as! String)
self.descriptions.append(object?.objectForKey("desc1") as! String)
The answer is so simple, but somehow the Parse.com docs don't have a single sample of it. Anyway I hope that helps anyone else who may get stuck at the same problem.

What should I do if a JSON file begins with an array?

So I am trying to use Swifty-JSON to go through a JSON file. The issue I am having though is that the JSON file (from the twitter API) starts with an array, an example is below:
[
{
"created_at": "Tue Mar 31 13:47:02 +0000 2015",
"id": 582901921171796000,
}
]
Lets say I wanted to read the created_at part, I would do the following:
let urlPath = "http://api.twitter.com/1.1/statuses/home_timeline.json?AUTHENTICATION_INFO"
let url: NSURL = NSURL(string: urlPath)!
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
if error != nil {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if err != nil {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
let json = JSON(jsonResult)
let createdAt = json[0]["created_at"].string!
println(createdAt)
})
task.resume()
This doesn't work though, I am retired with an error message which highlights my code and in the console (lldb) is printed out.
Does anybody know how to do this in Swifty-JSON, it is probably quit simple but I am very unsure.
Thanks
Cast the response as an NSArray in your NSJSONSerialization:
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSArray

Swift: Looping through a Dictionary Array

I'm struggling to loop through an array of dictionary values returned from a web service call.
I've implemented the following code and I seem to be encountering a crash on running.
I'd also like to store the results into a custom Struct. Really having difficulty achieving this and the answers on here so far haven't worked. Would be grateful if someone is able to help.
let nudgesURLString = "http://www.whatthefoot.co.uk/NUDGE/nudges.php"
let nudgesURL = NSURL(string: nudgesURLString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(nudgesURL!, completionHandler: {data, response, error -> Void in
if error != nil {
println(error)
} else {
let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
let nudges: NSDictionary = nudgesJSONResult["nudges"] as NSDictionary
if let list = nudgesJSONResult["nudges"] as? [[String:String]] {
for nudgeDict in list {
let location = nudgeDict["location"]
println(location)
}
}
}
})
task.resume()
}
NOTICE
This answer was written using Swift 1.2 and as such, there may be some slight stylistic and syntax changes required for the answer to work depending on your current Swift system.
Answer -- Swift 1.2
This line is crashing your code:
let nudges: NSDictionary = nudgesJSONResult["nudges"] as NSDictionary
You're forcing a cast that Swift can't handle. You never make it to your for-loop.
Try changing your code to look more like this:
let nudgesURLString = "http://www.whatthefoot.co.uk/NUDGE/nudges.php"
let nudgesURL = NSURL(string: nudgesURLString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(nudgesURL!, completionHandler: {data, response, error -> Void in
if error != nil {
println(error)
} else {
let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as [String : AnyObject]
if let nudges = nudgesJSONResult["nudges"] as? [[String : String]] {
for nudge in nudges {
let location = nudge["location"]
println("Got location: \(location)")
println("Got full nudge: \(nudge)")
}
}
}
})
task.resume()
Thanks,
I created the following Struct which stored the data, and also lets me create dictionaries in the view controller for a particular index.
struct NudgesLibrary {
var location: NSArray?
var message: NSArray?
var priority: NSArray?
var date: NSArray?
var nudges: NSArray?
init(nudgesObject: AnyObject) {
nudges = (nudgesObject["nudges"] as NSArray)
if let nudges = nudgesObject["nudges"] as? NSArray {
location = (nudges.valueForKey("location") as NSArray)
message = (nudges.valueForKey("message") as NSArray)
priority = (nudges.valueForKey("priority") as NSArray)
date = (nudges.valueForKey("date") as NSArray)
}
}
}

Resources