None of the success and failure blocks are getting executing - ios

This is my code
let url = URL(string: "http://demo6680989.mockable.io/getData")
let manager = AFHTTPSessionManager()
manager.get((url?.absoluteString)!, parameters: nil, progress: nil, success: {
(dataTask, responseObj) in
if let dict : NSDictionary = responseObj as? NSDictionary {
//print("Response: \(dict)")
AuditListParser().parseAudit(jsonData: dict)
}
}, failure: {
(dataTask, error) in
print(error.localizedDescription)
})
When I used this url in browser it is giving me some data but when i execute the above code it is neither going into success block nor fialure block.
1st time it was running properly and printed the data. I dont what happened suddenly, when i run it again this problem came
please help me

Normally, AFHTTPSessionManager's GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void ( ^ ) ( NSURLSessionDataTask *task , id responseObject ))success failure:(void ( ^ ) ( NSURLSessionDataTask *task , NSError *error ))failure method returns NSURLSessionDataTask object. So, you should start that task somehow for it to return in success or failure block. Just get the object that is being returned from get() method, and call resume() method of that object. Good luck!
EDIT
Like this:
let task = manager.get((url?.absoluteString)!, parameters: nil, progress: nil, success: {
(dataTask, responseObj) in
if let dict : NSDictionary = responseObj as? NSDictionary {
//print("Response: \(dict)")
AuditListParser().parseAudit(jsonData: dict)
}
}, failure: {
(dataTask, error) in
print(error.localizedDescription)
})
task.resume()

Related

Load twitter posts from different users

Hi need to load twitter posts from different users.
I know how to load post from single user.
Perform request with search query FROM:<username>.
Do you know the way how to load posts from different users?
I tried something like this FROM:<username1>&&<username2> - but it doesn't work.
Any ideas?
You can make use of TwitterKit framework which is available in cocoapods GitHub - https://github.com/twitter/twitter-kit-ios/wiki/Access-Twitter's-REST-API
Cocoapods - https://cocoapods.org/pods/TwitterKit
Its twitter's own library, so you can always rely on that.
To load multiple tweets you need to use the below code
let client = TWTRAPIClient()
let tweetIDs = ["510908888888487103", "510908133777777104"]
client.loadTweets(withIDs: tweetIDs) { (tweets, error) -> Void in
// handle the response or error
}
If you want to to access other Twitter API endpoints, you can construct a request manually also like below
let client = TWTRAPIClient()
let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/show.json"
let params = ["id": "20"]
var clientError : NSError?
let request = client.urlRequest(withMethod: "GET", url: statusesShowEndpoint, parameters: params, error: &clientError)
client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
if connectionError != nil {
print("Error: \(connectionError)")
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print("json: \(json)")
} catch let jsonError as NSError {
print("json error: \(jsonError.localizedDescription)")
}
}
Hope this one helps.
I found an approach. I have to use Twitter iOS SDK and TWTRAPIClient for performing the request. https://api.twitter.com/1.1/statuses/user_timeline.json is endpoint for getting tweets of certain user with some username.
NSURLRequest *r = [[TWTRAPIClient new] URLRequestWithMethod:#"GET"
URL:#"https://api.twitter.com/1.1/statuses/user_timeline.json"
parameters:#{#"screen_name":name}
error:nil];
[[TWTRAPIClient new] sendTwitterRequest:r completion:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if(data){
NSArray *tweets = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[TWTRTweet tweetsWithJSONArray:tweets]
}
}];

Indicated 'Anyobject' is not a subtype of 'NSProxy' when using AFNetworking

I'm using AFNetworking to retrieve weather info form openweathermap API.
let manager = AFHTTPSessionManager()
manager.requestSerializer = AFJSONRequestSerializer()
let url = "http://api.openweathermap.org/data/2.5/weather"
let params = ["lat": latitude,"lon": longitude,"cnt": 0]
manager.get(url, parameters: params,
success: {(operation: URLSessionDataTask,responseObject: AnyObject!) in print("JSON" + responseObject.description!) },
failure: {(operation: URLSessionDataTask?,error: Error) in print(error.localizedDescription)}
)
highlighting at responseObject.description indicated that 'Anyobject' is not a subtype of 'NSProxy'
If remove .description the error will disappear.
platform:xcode 8.3.2 swift:3
'Anyobject' is not a subtype of 'NSProxy'
First on of all the get method you are using is a deprecated one (I assume you have newest AFNetworking version). Please use the new one this way:
let manager = AFHTTPSessionManager()
manager.requestSerializer = AFJSONRequestSerializer()
let url = "http://api.openweathermap.org/data/2.5/weather"
let params = ["lat": 5.0,"lon": 5.0,"cnt": 0]
manager.get(url, parameters: params, progress: nil, success: { (operation, responseObject) in
if let responseObject = responseObject {
print(responseObject)
} else {
print("There is no response object") //assume parsing error for JSON
}
}) { (operation, error) in
print(error.localizedDescription)
}
As the last tip: if you are using Swift, better use Alamofire:
https://github.com/Alamofire/Alamofire
It supports lots of nice features coming from Swift and much nicer error handling. For example Alamofire treats parsing error as real errors and calls failure block, not success block like ANetworking.
Also allows you to easily integrate some JSON parsing libs like SwiftJSON
https://github.com/SwiftyJSON/SwiftyJSON

Receive response as NSDictionary instead of NSData

I'm trying to get the response from the server as NSDictionary instead of NSData, so first I'm using AFNetworking library and the server request these settings to be HTTP not JSON serializer as the following :
self.responseSerializer = AFHTTPResponseSerializer() as AFHTTPResponseSerializer
self.requestSerializer = AFHTTPRequestSerializer() as AFHTTPRequestSerializer
self.requestSerializer.HTTPMethodsEncodingParametersInURI = NSSet(array: ["GET"]) as! Set<String>
self.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json","text/json","text/javascript","text/html") as? Set<String>
Next is when i get the response from the server it comes to be NSData and its because I'm using AFHTTPRequestSerializer() and here is my code :
self.POST(addUserURL, parameters: dictionary, progress: nil, success: { (task, responseObject) -> Void in
print(responseObject)
}) { (task, error) -> Void in
}
Also inside AFNetworking block its not allowed to handle try and catch for NSJSONSerializtion which can be a possible solution but it doesn't work.
Use NSJSONSerialization for that as shown in below code :
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(responseObject, options: .AllowFragments) as! NSDictionary
// use jsonObject here
} catch {
print("json error: \(error)")
}
As response that you get from the server doesn't have top level object that is either Array or Dictionary you have to specify custom reading options in that should be used by AFNetworking.
In order to do that you have to set responseSerializer property on an instance of AFURLSessionManager class. You can do it as follows:
let sessionManager = OLFURLSessionManager.init() //you probably want to keep session manager as a singleton
sessionManager.responseSerializer = AFJSONResponseSerializer.serializerWithReadingOptions(.AllowFragments)
//you should use that instance of session manager to create you data tasks
After that you should be able to correctly parse response from the server as follows:

[NSURLSessionDataTask response]: unrecognized selector sent to instance

I have the following issue:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURLSessionDataTask response]: unrecognized selector sent to instance 0x7fced8599e60'
This is where it comes from:
GET("users/check_email", parameters: parameters, progress: nil, success: { sessionDataTask, response in
//the line with error
let statusCode = (sessionDataTask.response as? NSHTTPURLResponse)?.statusCode ?? 0
completionBlock(self.queryType?.mockStatusCode ?? statusCode, nil)
}) { sessionDataTask, error in
completionBlock(nil, NSError(responseError: error))
}
This happens when I try to mock a response. At some place of code I pass to success block:
var sessionDataTask = NSURLSessionDataTask()
success?(sessionDataTask, queryType?.mockResponse())
Something is wrong with sessionDataTask. NSURLSessionDataTask inherits from NSURLSessionTask which has response property. I don't know why I get this error.
If you declare your mock NSURLSessionDataTask like below, response will be nil.
Obj C:
NSURLSessionDataTask * sessionDataTask = [[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]] dataTaskWithURL:[NSURL URLWithString:#""]];
[sessionDataTask response];
Swift:
var sessionDataTask = NSURLSessionDataTask(NSURLSession(sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration()).dataTaskWithURL(NSURL(string: "")))
sessionDataTask.response()
Apple documentation says:
public class NSURLSessionTask : NSObject, NSCopying {
#NSCopying public var response: NSURLResponse? { get } /* may be nil if no response has been received */
}
So the only solution for this in Swift is:
var statusCode = 0
if sessionDataTask.respondsToSelector(Selector("response")) {
statusCode = (sessionDataTask.response as? NSHTTPURLResponse)?.statusCode ?? 0
}

I am trying to get my friend name and ids with graph api v2.4, but data returns empty:

hi i am trying to fetch Facebook friend list who using my app when i try this function i getting empty data
my sample code
let request: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/friends", parameters: nil, HTTPMethod: "GET")
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
print("Friends are : \(result)")
} else {
print("Error Getting Friends \(error)");
}
}
and my output is
FBSDKLog: starting with Graph API v2.4, GET requests for /me/friends should contain an explicit "fields" parameter
ID is: 964865453559288
2015-12-21 18:25:55.635[12226:218972] fb_id 964865453559288
Friends are : {
data = (
);
}
USE user_id to fetch friends.It is working fine . Try it
-(void)fetchFriendList:(NSString*)userid
{
NSString *string = [NSString stringWithFormat:#"/%#/taggable_friends",userid];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:string
parameters:nil];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
///// your results
}];
}

Resources