Why does my code break for one call to this method, but not another? - macos

I have a Mac application that is supposed to fetch Twitter followers and friends for a given username and then, in turn, ask Twitter for the user NAMES for each of those returned UserIDs. As you can see below, I have a method that will call the Twitter API to get friends/followers (which works fine). It is the userNameForUserID:delegate: method that is causing me problems. I used to do these requests synchronously and return the NSString for the username right then. That (now commented out) line always broke, so I tried doing it with an NSURLConnection asynchronously. Still doesn't work. I don't understand why
[[NSString alloc] initWithContentsOfURL:...] works for the fetchFollowers... method, but not when I do it the EXACT SAME way in the other...
I put a break point on the line that used to alloc init the NSString with contents of URL, and when I step into it, it doesn't break, return, throw an exception, crash...nothing. It's as if that line just got stepped over (but my application is still blocked.
Any ideas? Much appreciated!
NSString * const GET_FOLLOWERS = #"https://api.twitter.com/1/followers/ids.json?cursor=-1&screen_name=";
NSString * const GET_FRIENDS = #"https://api.twitter.com/1/friends/ids.json?cursor=-1&screen_name=";
NSString * const GET_USER_INFO = #"https://api.twitter.com/1/users/show.json?user_id=";
#implementation TwitterAPI
+ (void)userNameForUserID:(NSNumber *)userID delegate:(id<UserNameDelegate>)delegate
{
NSURL *url = [NSURL URLWithString:[GET_USER_INFO stringByAppendingString:[userID stringValue]]];
// NSString *JSON = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error) {
[delegate addUserNameToArray:data];
}];
}
+ (NSArray *)fetchFollowersWithUserName:(NSString *)userName
{
NSURL *url = [NSURL URLWithString:[GET_FOLLOWERS stringByAppendingString:userName]];
NSArray *followerIDs;
NSString *JSON = [[NSString alloc] initWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
if ([JSON rangeOfString:#"error"].location == NSNotFound)
followerIDs = [[JSON JSONValue] valueForKey:#"ids"];
return followerIDs;
}

Related

App terminates when using NSURL with parameters

In my app I sent a request to my PHP file to download some info. Whenever I use the code below it will terminate:
-(void)downloadItems
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *myString = [prefs stringForKey:#"commentsId"];
NSLog(#"The comments id is : %#",myString);
// Download the json file
NSString *urlstring = [NSString stringWithFormat:#"http:/MyWebSite.com/checkphp.php?title=%#", myString];
NSURL *jsonFileUrl = [NSURL URLWithString:urlstring];
NSLog(#"The qasida id is: %#", jsonFileUrl);
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}
But if I remove myString from urlString like this:
NSURL *jsonFileUrl = [NSURL URLWithString:#"http:/myWebSite/checkphp.php?title=%#"];
the app will not terminate and it will retrieve data.
Can any one tell me what is wrong with my code?
Thanks

An instance of class UITextField was deallocated while key value observers were still registered with it.

Hello i am getting this error
An instance 0x18872c0 of class UITextField was deallocated while key value observers were still registered with it. Observation info was leaked, and may even become mistakenly attached to some other object. Set a breakpoint on NSKVODeallocateBreak to stop here in the debugger.
I am observing changes made on a textfield in ViewDidLoad
[textNumber addObserver:self forKeyPath:#"text" options:0 context:nil];
this responds at here
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
if (textNumber.text.length==0) {
[buttonMakeAudioCall setImage:[UIImage imageNamed:#"off_green_btn.png"] forState:UIControlStateNormal];
buttonMakeAudioCall.userInteractionEnabled=NO;
}else{
[buttonMakeAudioCall setImage:[UIImage imageNamed:#"green_btn.png"] forState:UIControlStateNormal];
buttonMakeAudioCall.userInteractionEnabled=YES;
}
}
Unfortunately app crashes inside the following method when response comes.
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSString *balance = [greeting objectForKey:#"balance"];
NSLog(#"balance is %#",balance);
labelStatus.text=[NSString stringWithFormat:#"%#€",balance];
}
}];
What i understood is textfield object/observer is released at some point and i need to handle it.But how?I am using ARC.If somebody who knows better could provide more information on the situation,i could handle it.
I found out the reason.It was a mistake from my side.Just before entering this view controller ,I'm calling a method. where I'm writing the following code.
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *greeting = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSString *sipserver = [greeting objectForKey:#"ip"];
NSString *port = [greeting objectForKey:#"port"];
NSString *control_url = [greeting objectForKey:#"control_url"];
NSString *version = [greeting objectForKey:#"version"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self.navigationController popViewControllerAnimated:YES];
[[NSUserDefaults standardUserDefaults]setBool:YES forKey:#"login"];
The problem is this line.
[self.navigationController popViewControllerAnimated:YES];
Im poping a parent view controller of the current view controller.Because i've used blocks,this happens like this.Anyhow i found out the solution.This had nothing to do with textfield or key value observer.Hope this answer helps some one .Thanks.

Simple example of NSURLSession with authentication

I have written a REST service that serves up some data. It is passcode protected.
I am trying to write a background process that will grab the data and stuff it into a sqlLite db I have in the app.
I did this initially without authentication using :
- (void) callWebService {
dispatch_sync(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
scoularDirectoryURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
This worked fine but I don't think I can add authentication to that. If I can I would just use that.
What I am looking for is a nice, simple explanation of NSURLSession using user/password authentication.
I think your question is vague and underspecified. That said, here's one solution, from here:
-(void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)( NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
if (_sessionFailureCount == 0) {
NSURLCredential *cred = [NSURLCredential credentialWithUser:self.userName password:self.password persistence:NSURLCredentialPersistenceNone];
completionHandler(NSURLSessionAuthChallengeUseCredential, cred);
} else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
_sessionFailureCount++;
}
I strongly recommend that you read and re-read the Apple docs on this.
For me the following code works:
NSString *userName=#"user:";
NSString *userPassword=#"password";
NSString *authStr= [userName stringByAppendingString:userPassword];
NSString *url=#"http://000.00.0.0:0000/service.json";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: #"Basic %#",[authData base64EncodedStringWithOptions:0]];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
NSDictionary *theDictionary = [NSJSONSerialization JSONObjectWithData:data
options:0
error:NULL];
NSDictionary *host = [theDictionary objectForKey : #"host"];
// json nested
self.label.text = [host objectForKey:#"key1"];
self.label.text = [host objectForKey:#"key2"];
regards

Convert NSDictionary array values into NSString format for MFMailComposeViewController

I have a UIPickerViewDelegate that allows the user to select a term from the picker and see the term's definition by using NSDictionary to access data stored in a plist file. I also have a MFMailComposeViewController to allow the user to email the term and it's definition elsewhere.
But I can't seem to get the term and definition formatted properly for entry into the email. I looked at various "convert NSDictionary to NSString" solutions, but none seem to offer what I need, including variations of Term = [dict objectForKey:#"Term"].
Under viewDidLoad, I have the following:
NSString *path = [[NSBundle mainBundle] pathForResource:#"Glossary" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.termArray = [dict objectForKey:#"Term"];
self.definitionArray = [dict objectForKey:#"Definition"];
My pickerView code includes this:
NSString *resultString = [[NSString alloc] initWithFormat:
#"%#",
[definitionArray objectAtIndex:row]];
definitionLabel.text = resultString;
NSString *termString = [[NSString alloc] initWithFormat:
#"%#",
[termArray objectAtIndex:row]];
The code for showEmail contains:
int definitionIndex = [self.termPicker selectedRowInComponent:0];
NSString *emailTitle = [NSString stringWithFormat:#"Definition of %#", termLabel];
NSString *emailDefinition = [definitionArray objectAtIndex:definitionIndex];
NSString *messageBody = [NSString stringWithFormat:#"The definition of <B>%#</B> is:<P> <B>%#</B>", termLabel, emailDefinition];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
mc.mailComposeDelegate = self;
[mc setSubject:emailTitle];
[mc setMessageBody:messageBody isHTML:YES];
I would like the email title and message body to pull from the Term selected in the picker and the Definition associated with it. I'm sure it must be a simple formatting issue, but I can't figure it out.

XCode - UIWebView Not Loading

I have two local .html files in the Resources folder. I'm trying to load them the following way, but only the final page loads. What am I doing wrong?
File = please_wait.html
This one does not work.
NSError *error;
NSString* path = [[NSBundle mainBundle] pathForResource:#"please_wait" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
[webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
//Big "do-while" loop here. It works fine so I omitted it.
File = update_graph.html
This one does not work
path = [[NSBundle mainBundle] pathForResource:#"update_graph" ofType:#"html"];
htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
[webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
//Lots of code removed. All works correctly and doesn't touch webview
This last one works perfectly. Google displays.
string = #"http://google.com";
NSURL *url = [NSURL URLWithString: string];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
It appears from your comment that your UIWebView loads just fine, but it does not get a chance to refresh itself on the screen until you exit your method. It is not enough to set a break point inside the method and wait for the view to load: you must exit the method before iOS realizes that it needs to call UIWebView's drawRect method.
To fix this, split your method in three parts, A B and C, and set UIWebView's delegate in A to invoke B on webViewDidFinishLoad:, and the delegate in B to call C.
Here is how to implement this: start with a delegate that can call a selector when the loading has completed:
#interface GoToNext : NSObject <UIWebViewDelegate> {
id __weak target;
SEL next;
}
-(id)initWithTarget:(id)target andNext:(SEL)next;
-(void)webViewDidFinishLoad:(UIWebView *)webView;
#end
#implementation GoNext
-(id)initWithTarget:(id)_target andNext:(SEL)_next {
self = [super init];
if (self) {
target = _target;
next = _next;
}
return self;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[target performSelector:next];
#pragma clang diagnostic pop
}
#end
Now split your method into three parts - loading the first page, loading the second page, and loading the third page:
-(void)loadPleaseWait {
NSError *error;
NSString* path = [[NSBundle mainBundle] pathForResource:#"please_wait" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
webView.delegate = [[GoToNext alloc] initWithTarget:self andNext:#selector(loadUpdateGraph)];
[webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
// big do-while loop
}
-(void)loadUpdateGraph {
NSError *error;
NSString* path = [[NSBundle mainBundle] pathForResource:#"update_graph" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
webView.delegate = [[GoToNext alloc] initWithTarget:self andNext:#selector(loadGoogle)];
[webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
// Lots of code removed
}
-(void)loadGoogle {
string = #"http://google.com";
NSURL *url = [NSURL URLWithString: string];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
}

Resources