Issue in loading http://www.google.com url in iOS app - iphone

I was using the following code for checking the internet connection in my first iOS app (almost 3 years ago).
NSError *err = nil;
NSStringEncoding encoding;
NSString * connectionstring = [[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"] usedEncoding:&encoding error:&err];
if(connectionstring.length ==0)
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Error Occured" message:#"No Internet Connection." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
else
{
// loading another screen
}
The problem is in India and US it is going into the else condition but in Belgium it is going into the if condition and throwing the error. So are there any restrictions for Google in Belgium?
If it is tagged incorrectly please guide me. In my current versions solved this issue by using Rechability classes to check this . Just I wanted to know about it . Thanks in advance.

As a first step, look at the encoding.
You can log the encoding right after the connectionstring is created by inserting
NSLog(#"encoding: %#", [NSString localizedNameOfStringEncoding:encoding]);
into your code.
For further debugging, you could try loading the url into an NSData object first, then inspect the data and finally create a NSString from the data.

Alternative solution: To check internet connection Use Reachability class provided by apple.
Download Apple Sample Here, add Reachability class to your project.
- (BOOL)isConnected
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return !(networkStatus == NotReachable);
}

Instead of using google.com use any local client server test url for internet checking it will also be very fast responsive comparatively of any other way of internet validation.

Related

objective-c if NSURL fails display UIAlertView

I have this NSURL like so:
NSURL *url = [NSURL URLWithString:#"http://jamessuske.com/isthedomeopen/isthedomeopenGetData.php"];
and it works fine when I am connected to the internet. But if I am not (or if the user has no signal) I would want an UIAlertView to appear. I tried the following code below (with and without the if statement) but my app crashes.
if(!url){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Test Message"
message:#"This is a test"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
What Am I doing wrong?
What I mean by crashing, I mean my app opens and does not get the data from the URL. I do not see any errors, I just get brought to a page with this highlighter:
Thread 6
com.app.root.default-priority
- 0 ucol_getVersion
Next to it is a window with this hightlighted
0x17bbd32: movl 204(%ecx), %edx Thread 6: EXC_BAD_ACCESS (code=2 address=0xcc)
What you are doing only checks if the object url is a NULL pointer or not. If you want to check if a user has internet connection, I would recommend trying the Reachability classes, which can be found easily online. This one is very useful for me.
it is recommended to check the Internet availability if you are developing the app with internet connection requirement by the Apple and they are also providing the .h and .m files namely Reachability.h and Reachability.m so please download that files and import to your projects and there is a parameter named "internetConnectionStatus" and by that values use the below alert
if (internetConnectionStatus == NotReachable)
{
UIAlertView *responseAlert = [[UIAlertView alloc] initWithTitle:#"Network Error"
message:#"This application requires network connectivity."
delegate:self
cancelButtonTitle:#"Exit"
otherButtonTitles:#"Continue", nil];
[responseAlert show];
}
else
{ //do other stuff here
}
you can find the reachability files Here and you can use any Reachability files from github
ThnQ

NSStreamEventErrorOccurred triggered even if the network is pretty strong signal

I have implemented the NSStream delegate. I have implemented the same as Witap Application
In that, I have implemented handleEvent delegate
- (void) stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode{
switch(eventCode) {
case NSStreamEventOpenCompleted:
{
[tcpServer release];
tcpServer = nil;
break;
}
case NSStreamEventHasBytesAvailable:
{
//done my stuff here
}
case NSStreamEventErrorOccurred:
{
UIAlertView *wifiLostAlert = [[UIAlertView alloc] initWithTitle:#"Wifi
connection error" message:#"" delegate:nil cancelButtonTitle:#"Continue" otherButtonTitles:nil];
[wifiLostAlert show];
[wifiLostAlert release];
wifiLostAlert = nil;
}
}
In my client site, they reported an issue as
"Multiple time when we was either trying to send a message to the
learner or synching devices she got the following message: “Wifi
connection error.
Same happend at 2 different networks and it doesnot recover quickly
even if the network is pretty strong signal."
Unfortunately, I am unable to reproduce this issue in my site and it's working fine in another client site too!!.
Any clue's regarding the issue. Any help on this is appreciated.
Thank you.
I would recommend you supply the client with an updated version that displays more information about what error is actually occurring.
You can get more information about the error using:
NSError* error = [stream streamError];
You can find more information about NSError at NSError Class Reference.
Something like this might work in your case:
NSString* errorMessage = [NSString stringWithFormat:#"%# (Code = %d")",
[error localizedDescription],
[error code]];
Then change your UIAlertView to this:
UIAlertView *wifiLostAlert = [[UIAlertView alloc]
initWithTitle:#"Stream Error"
message:errorMessage
delegate:nil
cancelButtonTitle:#"Continue"
otherButtonTitles:nil];
This won't solve the problem but will give both you and your client more information about the root cause is.
For example, you may find the error is "Connection refused." which would point to a problem not with WiFi signal strength but in the server-side software.
Good luck!

ObjectiveFlickr Photo Upload Error

I'm working on using the ObjectiveFlickr library to upload photos to Flickr from my iPhone app. I am able to authorize the app and perform general requests, but I am getting an error while trying to upload a photo. The photo is meant to be uploaded is an image captured using AVFoundation. Here is the relevant code:
UIImage *image = [[UIImage alloc] initWithData:imageData];
if ([[AppDelegate sharedDelegate].apiContext.OAuthToken length]) {
NSData *uploadData = UIImageJPEGRepresentation(image, 1);
if (!flickrRequest) {
flickrRequest = [[OFFlickrAPIRequest alloc] initWithAPIContext:[AppDelegate sharedDelegate].apiContext];
flickrRequest.delegate = self;
flickrRequest.requestTimeoutInterval = 60.0;
}
[flickrRequest uploadImageStream:[NSInputStream inputStreamWithData:uploadData] suggestedFilename:#"Test" MIMEType:#"image/jpeg" arguments:[NSDictionary dictionaryWithObjectsAndKeys:#"0", #"is_public", nil]];
[UIApplication sharedApplication].idleTimerDisabled = YES;
NSLog(#"Can upload photo");
The flickrRequest object is defined and #property'd in the .h file pertaining to the code above.
The OFFlickrRequestDelegate methods are as follows:
- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest imageUploadSentBytes:(NSUInteger)inSentBytes totalBytes:(NSUInteger)inTotalBytes {
NSLog(#"Success");
}
- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didCompleteWithResponse:(NSDictionary *)inResponseDictionary {
NSLog(#"%s %# %#", __PRETTY_FUNCTION__, inRequest.sessionInfo, inResponseDictionary);
}
- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didFailWithError:(NSError *)inError {
NSLog(#"%s %# %#", __PRETTY_FUNCTION__, inRequest.sessionInfo, inError);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[inError description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
When I run the project on the device the console shows:
Can upload photo
Success
Success
Success
Success
flickrAPIRequest:didFailWithError:(null) Error Domain=org.lukhnos.ObjectiveFlickr Code=2147418115 "The operation couldn’t be completed. (org.lukhnos.ObjectiveFlickr error 2147418115.)"
Searching through the API's documentation, "error 2147418115" is defined as "OFFlickrAPIRequestFaultyXMLResponseError". I'm not really sure what this means though. Also strange--"Success" appears four times when I'm only attempting to upload one photo.
The sample app utilizing ObjectiveFlickr, "Snap and Run" uploads photos fine on the same device that I am testing on. Comparing the code between my app and Snap and Run, I don't see any major differences that could cause the photo not to upload.
Any help would be greatly appreciated.
That is strange. OFFlickrAPIRequestFaultyXMLResponseError means the returned data cannot be parsed as XML. If the sample app SnapAndRun runs correctly and yours don't, I suggest add one line in ObjectiveFlickr.m, right after the line NSString *stat = [rsp objectForKey:#"stat"];:
NSString *dataString = [[[NSString alloc] initWithData:[request receivedData] encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"received response: %#", dataString);
This may help you find out what goes wrong (e.g. if it's a server-side issue, or some response format that the library missed).
When I got this error I used Charles to see what was going on. Flickr was sending back an error saying that the signature was invalid. Looking at my request, I found that I had reversed the order of the key and values (i.e. there was whitespace in one of my keys, which probably caused a signature error).

How to send an email to a receipent in background in iOS5?

In an iPhone app,I want to send an email to a person who has forgotten about their passcode . I want to send the mail in background (cant use MFMailComposeViewController for this) and also the app must not be pushed to background . Is there a way to achieve this?
The best way of doing this is using SKPSMTPMessage. You can download it from here: https://github.com/jetseven/skpsmtpmessage This is a very easy solution that I have used before for using "Forgot Password" solutions in iOS apps. To implement simply drag the downloaded files into your application, #import the the "SKPSMTPMessage.h" into your class, and implement the following code:
.h
#import "SKPSMTPMessage.h"
#interface SomeView : UIViewController <SKPSMTPMessageDelegate> {
}
- (IBAction)forgotPassword;
.m
- (IBAction)forgotPassword {
SKPSMTPMessage *forgotPassword = [[SKPSMTPMessage alloc] init];
[forgotPassword setFromEmail:#"some-email#gmail.com"]; // Change to your email address
[forgotPassword setToEmail:#"user-email#gmail.com"]; // Load this, or have user enter this
[forgotPassword setRelayHost:#"smtp.gmail.com"];
[theMessage setRequiresAuth:YES]; // GMail requires this
[forgotPassword setLogin:#"some-email#gmail.com"]; // Same as the "setFromEmail:" email
[forgotPassword setPass:#"password"]; // Password for the Gmail account that you are sending from
[forgotPassword setSubject:#"Forgot Password: My App"]; // Change this to change the subject of the email
[forgotPassword setWantsSecure:YES]; // Gmail Requires this
[forgotPassword setDelegate:self]; // Required
NSString *newpassword = #"helloworld";
NSString *message = [NSString stringWithFormat:#"Your password has been successfully reset. Your new password: %#", newpassword];
NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:#"text/plain", kSKPSMTPPartContentTypeKey, message, kSKPSMTPPartMessageKey, #"8bit" , kSKPSMTPPartContentTransferEncodingKey, nil];
[forgotPassword setParts:[NSArray arrayWithObjects:plainPart, nil]];
[forgotPassword send];
}
Also be sure to include the following methods in the .m. You can change the contents of the UIAlertViews depending on what you want to display to the user.
- (void)messageSent:(SKPSMTPMessage *)message {
NSLog(#"Message Sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Password Reset" message:#"Check your email for your new password." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error {
NSLog(#"Message Failed With Error(s): %#", [error description]);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There was an error reseting your password. Please try again later." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
You also need to do the following before this will work.
Your Target -> Get Info -> Build -> All Configurations -> Other Link Flags: "-ObjC"
If you need help with this, see http://developer.apple.com/qa/qa2006/qa1490.html
EDIT:
* CFNetwork.framework must also be added for this to work! *
Let me know if you have any more questions.
Thanks,
Jacob
You can't use MFMailComposeViewController to do this. No API will allow you to send emails or any kind of message on behalf of the user without he seeing it.
The only I see is to make a call to your server and the server send the email, something like this:
NSURLRequest requestWithURL:[NSURL urlWithString:#"http://server.com/send_passcode?to=email#lala.com"]];
You cannot send SMS/Email without user acceptance. But there are a lot of web-services in internet which can send SMS/Email. I guess some app uses those services or uses own.
You CAN send email in the background (without using the default MFMail Controller). BUT you still need the user to fill out whatever form (or content you want to email) and have them click "Send".
Here is my post on how to do it. It includes code and images.
Locking the Fields in MFMailComposeViewController
P.S. this works and Apple has approved over 10 of my apps that use this code/method.
In reference to the PostageApp comment below if you wanted to send emails without any hassle of setting up an SMTP client you can check out the PostageKit wrapper for using the PostageApp service. Let's you send emails with a couple lines of code reliably.
https://github.com/twg/PostageKit
May be you should implement PHP script that will send out email to user. In ios, you can use POST method in NSURLConnection to call PHP script. You can find many scripts on Google to send out email to user.
Download SKPSMTP Library and import
#import "SKPSMTPMessage.h"
#import "NSData+Base64Additions.h"
-(IBAction)btnRecoverClicked:(id)Sender;
Then implement the method for sending mail in background.
-(IBAction) btnRecoverClicked:(id)sender {
NSString *str=#"Your password is:";
NSString *strUserPassword=[NSString stringWithFormat:#"%# %#",str,struserPassword];
NSLog(#"Start Sending");
SKPSMTPMessage *emailMessage = [[SKPSMTPMessage alloc] init];
emailMessage.fromEmail = #"XXXXX"; //sender email address
emailMessage.toEmail = struserEmail; //receiver email address
emailMessage.relayHost = #"smtp.gmail.com";
//emailMessage.ccEmail =#"your cc address";
//emailMessage.bccEmail =#"your bcc address";
emailMessage.requiresAuth = YES;
emailMessage.login = #"xxxxxxxx"; //sender email address
emailMessage.pass = #"XXXXXXX"; //sender email password
emailMessage.subject =#"Password Recovery";
emailMessage.wantsSecure = YES;
emailMessage.delegate = self; // you must include <SKPSMTPMessageDelegate> to your class
NSString *messageBody = [NSString stringWithFormat:#"Your password is: %#",struserPassword]
;
//for example : NSString *messageBody = [NSString stringWithFormat:#"Tour Name: %#\nName: %#\nEmail: %#\nContact No: %#\nAddress: %#\nNote: %#",selectedTour,nameField.text,emailField.text,foneField.text,addField.text,txtView.text];
// Now creating plain text email message
NSDictionary *plainMsg = [NSDictionary
dictionaryWithObjectsAndKeys:#"text/plain",kSKPSMTPPartContentTypeKey,
messageBody,kSKPSMTPPartMessageKey,#"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,nil];
//in addition : Logic for attaching file with email message.
/*
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"filename" ofType:#"JPG"];
NSData *fileData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *fileMsg = [NSDictionary dictionaryWithObjectsAndKeys:#"text/directory;\r\n\tx-
unix-mode=0644;\r\n\tname=\"filename.JPG\"",kSKPSMTPPartContentTypeKey,#"attachment;\r\n\tfilename=\"filename.JPG\"",kSKPSMTPPartContentDispositionKey,[fileData encodeBase64ForData],kSKPSMTPPartMessageKey,#"base64",kSKPSMTPPartContentTransferEncodingKey,nil];
emailMessage.parts = [NSArray arrayWithObjects:plainMsg,fileMsg,nil]; //including plain msg and attached file msg
*/
[emailMessage send];
// sending email- will take little time to send so its better to use indicator with message showing sending...
}
To handle the success and fail use
-(void)messageSent:(SKPSMTPMessage *)message{
NSLog(#"delegate - message sent");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message sent to your mail." message:nil delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
and
-(void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error{
// open an alert with just an OK button
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
NSLog(#"delegate - error(%d): %#", [error code], [error localizedDescription]);
}
https://github.com/troyz/MailUtil
I have used library above to send mail in background, so it works.
pod "MailUtil", :git => 'https://github.com/troyz/MailUtil.git', :tag => '0.1.0'
Swift code is here:
import MailUtil
SendEmailOperation.setupConfig(withServer: "smtp.foo.com", withFrom: "foo#mailserver.com", withLogin: "foo#mailserver.com", withPassword: "*********")
let operation = SendEmailOperation(to: "foo#mailserver.com", subject: "Hello", body: "world", path: "/selected/path/for/your/file.pdf")
operation?.completionBlock = {
debugPrint("Mail sent!")
DispatchQueue.main.async {
//showMailSentPopup()
}
}
do {
try SendEmailOperation.sendEmail(operation)
} catch {
debugPrint("Mail could not sent or sending result could not handle - \(error)")
}

Getting Facebook ID number with API

I know - I have read the documentation - but frankly Facebook is horrible at it. I can't figure out how to send a request that illicits a response. Here's what I'm trying:
NSURL *fbID = [NSURL URLWithString:#"https://graph.facebook.com/me?fields=id"];
fbUserID = [[NSData alloc] initWithContentsOfURL: fbID];
Where should this code go? Is there a specific class it is looking for if I have set 'self' as delegate?
How are you trying to integrate FB into your app? I have been looking into Facebook connect recently and found their documentation very helpful (http://developers.facebook.com/docs/guides/mobile/#ios). I know you said you looked at the documentation, but for me after going through their steps for iOS I was able to make an app that allowed users to sign in and give me access to their basic information, including ID. After going through authorization, I had the following code in my app delegate:
- (void) fbDidLogin {
//get information about the currently logged in user
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
- (void)request:(FBRequest *)request didLoad:(id)result {
NSString *name = [result objectForKey:#"name"];
NSString *msg = [[NSString alloc] initWithFormat:#"To prove this works, your name is %#",name];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Thanks for Logging In!"
message:msg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
This gets the user's full name after logging in and displays it. You can do the same thing for getting their ID.