didFailLoadWithError being called only for iOS7.
This method is not called for iOS6.
The error logged is:
ERROR : Error Domain=NSURLErrorDomain Code=-999 "The operation
couldn’t be completed. (NSURLErrorDomain error -999.)"
UserInfo=0xcd0e200
{NSErrorFailingURLKey=bsp.gov.ph/statistics/sdds/exchrate.htm,
NSErrorFailingURLStringKey=bsp.gov.ph/statistics/sdds/exchrate.htm}
The error code -999 apparently is a URL Cancelled request but I am using the same code for iOS6 and works perfectly fine.
Why does it show an error for ios7?
The code I am using is:
- (void)viewDidLoad
{
[super viewDidLoad];
isFirstTime=TRUE;
ratesArray=[[NSArray alloc]initWithObjects:#"In",#"USD",#"JPY",#"GBP",#"HKD",#"CAD",#"SGD",#"AUD",#"SAR",#"THB",#"AED",#"CNY",#"KRW",#"EUR",#"MYR",#"TWD", nil];
NSLog(#"rates.count = %d",ratesArray.count);
defaults = [NSUserDefaults standardUserDefaults];
[self loadServerData];
}
-(void)loadServerData
{
GeneralClass *gen=[GeneralClass retrieveSingleton];
euroRatesArray =[[NSMutableArray alloc]init];
[euroRatesArray addObject:#"EURO"];
usRatesArray =[[NSMutableArray alloc]init];
[usRatesArray addObject:#"US"];
phpRatesArray =[[NSMutableArray alloc]init];
[phpRatesArray addObject:#"PHP"];
self.navigationController.navigationBar.hidden=TRUE;
if ([gen checkNetworkConnection] ) {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//Create a URL object.
NSURL *url = [NSURL URLWithString:#"http://www.bsp.gov.ph/statistics/sdds/exchrate.htm"];
//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
//Load the request in the UIWebView.
[webPage loadRequest:requestObj];
} else {
defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:kExchanteRatesKey];
NSArray *contentArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
lblDate.text=[defaults objectForKey:kExchanteRateDate];
if (contentArray.count>0) {
for (int i=1; i<contentArray.count-1; i++) {
RateClass *rate=(RateClass *)[contentArray objectAtIndex:i];
[euroRatesArray addObject:(rate.text2.length>0 ? rate.text2:#"")];
[usRatesArray addObject:(rate.text3.length>0 ? rate.text3:#"")];
[phpRatesArray addObject:(rate.text4.length>0 ? rate.text4:#"")];
}
}
//NSLog(#"euroRatesArray = %#",euroRatesArray);
//NSLog(#"usRatesArray = %#",usRatesArray);
//NSLog(#"phpRatesArray = %#",phpRatesArray);
[activity setHidden:TRUE];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
[self hideActivityBar];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[self hideActivityBar];
}
-(void) hideActivityBar
{
[self htmlParse];
}
-(void)htmlParse
{
//NSString *html = [webPage stringByEvaluatingJavaScriptFromString: #"document.getElementById('exchrate_28426').innerHTML"];
//NSString *html = [webPage stringByEvaluatingJavaScriptFromString: #"document.getElementsByClassName('xl6528426')[0].innerHTML"];
NSString *html = [webPage stringByEvaluatingJavaScriptFromString:#"document.body.innerText"];
NSArray *array=[html componentsSeparatedByString:#"\n"];
NSLog(#"array.count = %d",array.count);
int checkRateIndex=1;
int index=212;
NSUserDefaults *standardUserDefaults=[NSUserDefaults standardUserDefaults];
}
Related
I have one login screen after that it will move to next view controller which have i have used some networks like http,json to get data from server. when i enter login username/password then if i click login button its getting delay to 8 seconds after that only it moving to next view controller.Still that my login screen alone showing for 8 seconds and then only it move to next view controller.
Here my login controller.m:
#implementation mainViewController
- (void)viewDidLoad {
[super viewDidLoad];
_username.delegate = self;
_password.delegate = self;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults boolForKey:#"reg"]) {
NSLog(#"no user reg");
_logBtn.hidden = NO;
}
}
- (void)viewWillAppear:(BOOL)animated
{
[self.navigationController setNavigationBarHidden:YES animated:animated];
[super viewWillAppear:animated];
_username.text = nil;
_password.text = nil;
}
- (IBAction)LoginUser:(id)sender {
if ([_username.text isEqualToString:#"sat"] && [_password.text isEqualToString:#"123"]) {
NSLog(#"Login success");
[self performSegueWithIdentifier:#"nextscreen" sender:self];
}
else {
NSLog(#"login was unsucess");
// Alert message
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"wrong"
message:#"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil];
[alertController addAction:actionOk];
[self presentViewController:alertController animated:YES completion:nil];
}
}
Here my nextcontroller.m
- (void)viewDidLoad {
[super viewDidLoad];
//for search label data
self.dataSourceForSearchResult = [NSArray new];
//collection of array to store value
titleArray = [NSMutableArray array];
// here only i am getting data from server
[self getdata];
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView reloadData];
}
Help me out. If my question din't understand.I can tell more about my post. And in my nextcontroller.m [self getdata] is i am getting data from server url.Thanks
My get data:
-(void)getdata {
NSString *userName = #“users”;
NSString *password = #“images”;
NSData *plainData = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainData base64EncodedStringWithOptions:0];
base64String=[self sha256HashFor: base64String];
NSString *urlString = #"https://porterblog/image/file”;
NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"GET"];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", userName, base64String];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSError * error;
self->arrayPDFName = [[NSMutableArray alloc]init];
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dictOriginal = jsonResults[#“birds”];
[titleArray addObject:[NSString stringWithFormat:#" birds(%#)”, dictOriginal[#"count"]]];
NSDictionary *dictOriginal2 = jsonResults[#"owl”];
[titleArray addObject:[NSString stringWithFormat:#" Owl(%#)”, dictOriginal2[#"count"]]];
NSDictionary *dictOriginal3 = jsonResults[#"pensq”];
[titleArray addObject:[NSString stringWithFormat:#" Pensq(%#)”, dictOriginal3[#"count"]]];
NSDictionary *dictOriginal4 = jsonResults[#“lion”];
[titleArray addObject:[NSString stringWithFormat:#" lion(%#)”, dictOriginal4[#"count"]]];
NSArray *arrayFiles = [NSArray arrayWithObjects: dictOriginal, dictOriginal2, dictOriginal3, dictOriginal4, nil];
NSLog(#"str: %#", titleArray);
for (NSDictionary *dict in arrayFiles) {
NSMutableArray *arr = [NSMutableArray array];
NSArray *a = dict[#"files"];
for(int i=0; i < a.count; i ++) {
NSString *strName = [NSString stringWithFormat:#"%#",[[dict[#"files"] objectAtIndex:i] valueForKey:#"name"]];
[arr addObject:strName];
}
[arrayPDFName addObject:arr];
}
NSString *errorDesc;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory1 = [paths objectAtIndex:0];
NSString *plistPath = [documentsDirectory1 stringByAppendingPathComponent:#"SampleData.plist"];
NSString *error1;
returnData = [ NSPropertyListSerialization dataWithPropertyList:jsonResults format:NSPropertyListXMLFormat_v1_0 options:0 error:&error];
if(returnData ) {
if ([returnData writeToFile:plistPath atomically:YES]) {
NSLog(#"Data successfully saved.");
}else {
NSLog(#"Did not managed to save NSData.");
}
}
else {
NSLog(#"%#",errorDesc);
}
NSDictionary *stringsDictionary = [NSDictionary dictionaryWithContentsOfFile:plistPath];
}
EDITED:
`- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
self.dataSourceForSearchResult = [NSArray new];
titleArray = [NSMutableArray array];
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
[self.collectionView reloadData];
self.navigationItem.hidesBackButton = YES;
});
});
}`
You're getting your data using main thread you need do to that in background then invoke the code you need (as i see is reload collectionView)
I assume that because you didn't show the getdata method code
If that the case you can use this code:
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self.collectionView reloadData];
});
});
It's mean that your VC will show immediately but the collectionView fill after you finish load the data, you can put some old data while loading like Facebook app (you see latest retrieved posts until finish loading].
Edit:
In your code you replace viewdidload method in nextController with next code:
- (void)viewDidLoad {
[super viewDidLoad];
//for search label data
self.dataSourceForSearchResult = [NSArray new];
//collection of array to store value
titleArray = [NSMutableArray array];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Tasks
[self getdata];
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
[self.collectionView reloadData];
});
});
self.collectionView.dataSource = self;
self.collectionView.delegate = self;
}
I am using tumbler login authentication via oauth. I am following this url: http://codegerms.com/login-with-tumblr-in-uiwebview-using-xcode-6-part-3/
for login authentication and get Access token and Secret Key for Tumblr API in iOS via login in UIWebview.
I am using this block of code.
- (void)viewDidLoad {
[super viewDidLoad];
// clientID = #"Tjta51N6kF6Oxmm1f3ytpUvMPRAE1bRgCgG90SOa0bJMlSlLeT";
// secret = #"lrlQPNx3Yb1nRxp4qreYXvUURkGUmYCBoQacOmLTDRJAc7awRN";
clientID = #"sdF0Y6bQoJYwfIB1Mp7WECwobAgnq5tmkRjo7OXyKHDg3opY7Y";
secret = #"qJNGrRjyriZBeBhcgJz0MAcD9WAYXUW1tLbLrbYE4ZclzAUH9g";
redirect = #"tumblr://authorized";
[self.WebView setBackgroundColor:[UIColor clearColor]];
[self.WebView setOpaque:NO];
[self connectTumblr];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)connectTumblr {
consumer = [[OAConsumer alloc]initWithKey:clientID secret:secret];
NSURL* requestTokenUrl = [NSURL URLWithString:#"http://www.tumblr.com/oauth/request_token"];
OAMutableURLRequest* requestTokenRequest = [[OAMutableURLRequest alloc] initWithURL:requestTokenUrl
consumer:consumer
token:nil
realm:nil
signatureProvider:nil] ;
OARequestParameter* callbackParam = [[OARequestParameter alloc] initWithName:#"oauth_callback" value:redirect] ;
[requestTokenRequest setHTTPMethod:#"POST"];
[requestTokenRequest setParameters:[NSArray arrayWithObject:callbackParam]];
OADataFetcher* dataFetcher = [[OADataFetcher alloc] init] ;
[dataFetcher fetchDataWithRequest:requestTokenRequest
delegate:self
didFinishSelector:#selector(didReceiveRequestToken:data:)
didFailSelector:#selector(didFailOAuth:error:)];
}
- (void)didReceiveRequestToken:(OAServiceTicket*)ticket data:(NSData*)data {
NSString* httpBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
requestToken = [[OAToken alloc] initWithHTTPResponseBody:httpBody];
NSURL* authorizeUrl = [NSURL URLWithString:#"https://www.tumblr.com/oauth/authorize"];
OAMutableURLRequest* authorizeRequest = [[OAMutableURLRequest alloc] initWithURL:authorizeUrl
consumer:nil
token:nil
realm:nil
signatureProvider:nil];
NSString* oauthToken = requestToken.key;
OARequestParameter* oauthTokenParam = [[OARequestParameter alloc] initWithName:#"oauth_token" value:oauthToken] ;
[authorizeRequest setParameters:[NSArray arrayWithObject:oauthTokenParam]];
// UIWebView* webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
// webView.scalesPageToFit = YES;
// [[[UIApplication sharedApplication] keyWindow] addSubview:webView];
// webView.delegate = self;
[self.WebView loadRequest:authorizeRequest];
}
#pragma mark UIWebViewDelegate
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(#"scheme: %#",[[request URL] scheme]);
if ([[[request URL] scheme] isEqualToString:#"tumblr"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"oauth_verifier"]) {
verifier = [keyValue objectAtIndex:1];
break;
}
}
if (verifier) {
NSURL* accessTokenUrl = [NSURL URLWithString:#"https://www.tumblr.com/oauth/access_token"];
OAMutableURLRequest* accessTokenRequest = [[OAMutableURLRequest alloc] initWithURL:accessTokenUrl
consumer:consumer
token:requestToken
realm:nil
signatureProvider:nil];
OARequestParameter* verifierParam = [[OARequestParameter alloc] initWithName:#"oauth_verifier" value:verifier];
[accessTokenRequest setHTTPMethod:#"POST"];
[accessTokenRequest setParameters:[NSArray arrayWithObject:verifierParam]];
OADataFetcher* dataFetcher = [[OADataFetcher alloc] init];
[dataFetcher fetchDataWithRequest:accessTokenRequest
delegate:self
didFinishSelector:#selector(didReceiveAccessToken:data:)
didFailSelector:#selector(didFailOAuth:error:)];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(#"webView error: %#",error);
// ERROR!
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
[spinner setHidden:NO];
[spinner startAnimating];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[spinner setHidden:YES];
[spinner stopAnimating];
}
- (void)didReceiveAccessToken:(OAServiceTicket*)ticket data:(NSData*)data {
NSString* httpBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
accessToken = [[OAToken alloc] initWithHTTPResponseBody:httpBody];
NSString *OAuthKey = accessToken.key; // HERE YOU WILL GET ACCESS TOKEN
NSString *OAuthSecret = accessToken.secret; //HERE YOU WILL GET SECRET TOKEN
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Tumblr Token"
message:OAuthSecret
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
Every thing is working fine but when logged in then
if ([[[request URL] scheme] isEqualToString:#"tumblr"]) {
}
should called in shouldStartLoadWithRequest delegate method
but the given condition is not satisfied. so that I am unable to verify oauth_verifier and unable to get accessToken.
Please Advice Thanks.
You must be use https instead of http for every url of Tumblr.It will work perfectly.
Thanks.
I am doing a database based application. My app needs to update a database table and simultaneously it needs to update the table view i.e. generated based on that particular database table.
Here's is the code i have written
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.courses.count;
}
-(void)viewWillAppear:(BOOL)animated {
self.usernameLBL.text = [NSString stringWithFormat:#"Welcome, %#", self.del.username];
[self loadCourses];
// NSLog(#"The courses count is %d", self.courses.count);
}
-(void)loadCourses {
NSString * stringUrl = [NSString stringWithFormat:"Some URL";
NSURL * uRL = [NSURL URLWithString:[stringUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:uRL];
NSError * error;
NSData * results = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
self.courses = [NSJSONSerialization JSONObjectWithData:results options:0 error:&error];
NSLog(#"The courses array count is %d", self.courses.count);
[self.tableView reloadData];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSDictionary * dict = self.courses[indexPath.row];
cell.textLabel.text = dict[#"name"];
cell.detailTextLabel.text = dict[#"id"];
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.courses = [[NSMutableArray alloc] init];
self.del = [[UIApplication sharedApplication] delegate];
NSString * strURL = [NSString stringWithFormat:"Some URL";
// NSLog(#"The username is %#", self.del.username);
NSURL * url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
// NSLog(#"The data is %#", data);
NSDictionary * result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
// NSLog(#"The error is %#", error);
// NSLog(#"The value returned is %#", result[#"image"]);
if(![result[#"image"] isEqualToString:#"empty"]){
NSString * urlLocation = result[#"image"];
self.adminIMG.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[urlLocation stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]]];
}
// Do any additional setup after loading the view.
}
- (IBAction)addNewCourse:(id)sender {
NSString * strURL = [NSString stringWithFormat:"Some URL";
NSURL * url = [NSURL URLWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * results = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:results options:0 error:&error];
if([dict[#"response"] isEqualToString:#"success"]) {
NSLog(#"New course added");
UIAlertView * success = [[UIAlertView alloc] initWithTitle:#"New course added successfully" message:#"You successfully added a new course" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[success show];
}else {
NSLog(#"Course not added");
}
[self.courses removeAllObjects];
[self viewDidLoad];
[self viewWillAppear:YES];
}
And i got this error.
Error: Evaluation[13335:60b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKeyedSubscript:]: unrecognized selector sent to instance 0xb7d26d0'
I tried many solutions available on the internet but those are not working for me. Anyone can help me, please. Thanks in advance :)
your issue might be here
[self.courses removeAllObjects];
[self viewDidLoad];
[self viewWillAppear:YES];
you don't have to clear your array, try this:
function:
- (void)addCourse{
NSString * strURL = [NSString stringWithFormat:"Some URL";
NSURL * url = [NSURL URLWithString:
[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest * request = [NSURLRequest requestWithURL:url];
NSError * error;
NSData * results = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:&error];
NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:results
options:0 error:&error];
if([dict[#"response"] isEqualToString:#"success"]) {
NSLog(#"New course added");
UIAlertView * success = [[UIAlertView alloc]
initWithTitle:#"New course added successfully"
message:#"You successfully added a new course"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[success show];
}else {
NSLog(#"Course not added");
}
}
Your IBAction keep it simple there you don't want to fire off life cycle event from an IBAction instead call the methods you need not to mention that it is not a good idea to call viewDidLoad before viewWillAppear Method...
- (IBAction)addNewCourse:(id)sender {
[self addCourse];
[self loadCourses];
}
first you check the array data it valid or not .(put break point and check it)
and i think u got error because u still not convert integer to string .
i replace this line in to tableview cellForRowAtIndexPath:
cell.detailTextLabel.text = dict[#"id"];
to replace
cell.detailTextLabel.text =[NSString stringWithFormat:#"%d",dict[#"id"]];
Its may be very helpful to you Thanks.
I think your problem is here.. your targeting AppDelegate as self.delegate
self.del = [[UIApplication sharedApplication] delegate];
And AppDelegate runs onetime at start of application only that's why your are getting error
My application used notify of APNS. When server send a notify to client with a link. I click to notify on notification bar, application will open link in notify on webview. My problem is, when application run active or Background, it run normal and load link OK. But when application don't active, i click to notify, it will don't load link in notify, it only load old link in NSUserDefaults or link "http://staging.nhomxe.vn". This is my code:
APPDELEGATE.m
- (void)application:(UIApplication*)application
didReceiveRemoteNotification:
(NSDictionary*)userInfo
{
NSLog(#"Received notification: %#", userInfo);
NSDictionary *data = [ userInfo objectForKey:#"aps"];
for(NSString *key in data) {
NSString *info = [data objectForKey:key];
NSLog(#"thong tin nhan dc: %# : %#", key, info);
}
NSString *message = [userInfo valueForKey:#"link"] ;
//NSArray *info = [message componentsSeparatedByString:#"&#"];
//NSString *body = [info objectAtIndex:0];
//NSString *link = [info objectAtIndex:1];
NSLog(#"Thong tin Link: %#",message);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:message forKey:#"LINK"];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Warning"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alertView show];
ViewController *vc = (ViewController *)self.window.rootViewController;
NSURL *url = [NSURL URLWithString:message];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[vc.webView loadRequest:urlRequest];
[vc.webView3 loadRequest:urlRequest];
}
MYVIEWCONTROLLER.m
- (void)viewDidLoad
{ NSString *link = NULL;
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
link = [data objectForKey:#"LINK"];
NSString *connect = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://staging.nhomxe.vn"] encoding:NSUTF8StringEncoding error:nil];
if(connect == NULL)
{
NSLog(#"Server hiện tại đang bảo trì. Ứng dụng sẽ đóng ngay bây giờ.!");
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:#"Warning"
message:#"Server hiện tại đang bảo trì. Ứng dụng sẽ đóng ngay bây giờ."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
alert.tag = 1;
[alert show];
}else
{ if(link == NULL)
{
NSString *linkWeb = #"http://staging.nhomxe.vn";
NSURL *url = [NSURL URLWithString:linkWeb];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:urlRequest];
[self.webView3 loadRequest:urlRequest];
}else{
NSURL *url = [NSURL URLWithString:link];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:urlRequest];
[self.webView3 loadRequest:urlRequest];
//[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"LINK"];
//[[NSUserDefaults standardUserDefaults] synchronize];
//NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//[defaults setValue:NULL forKey:#"LINK"];
}
}
// Schedule the runScheduledTask in 5 seconds
aTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:#selector(runScheduledTask) userInfo:nil repeats:YES];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
When App is not running in Background
- (void)application:(UIApplication*)application
didReceiveRemoteNotification:
(NSDictionary*)userInfo
Would not be called you Should handle your data something like this..
In your AppDelegate.m within didFinishLaunchingWithOptions method do something like this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSDictionary* userInfo = [launchOptions valueForKey:#"UIApplicationLaunchOptionsRemoteNotificationKey"];
NSDictionary * data = [userInfo objectForKey:#"aps"];
for(NSString *key in data) {
NSString *info = [data objectForKey:key];
NSLog(#"thong tin nhan dc: %# : %#", key, info);
}
//.…COntinue with your Execution So on…. You will get the data in the Data Dictionary which you are looking for
}
I suspect you don't have code to start app from notification.
Take a look at - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions. If app starts from notification, you'll have launchOptions.
If you have remote notification, you'll have UIApplicationLaunchOptionsRemoteNotificationKey key in launchOptions.
UIApplicationLaunchOptionsRemoteNotificationKey
The presence of this key indicates that a remote notification is available for the
app to process. The value of this key is an
NSDictionary containing the payload of the remote notification. See
the description of application:didReceiveRemoteNotification: for
further information about handling remote notifications.
I am beginner iOS apps developer .I have tried following link codes.It's playing good but I need selected audio file path and how to upload to server in selected audio,kindly help out.Audio code Reference url
-(IBAction)clickFileuploadbtn:(id)sender;
{
NSLog(#"2");
picker1 =
[[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker1.delegate = self;
picker1.allowsPickingMultipleItems = YES;
picker1.prompt = NSLocalizedString (#"Add songs to play", "Prompt in media item picker");
// The media item picker uses the default UI style, so it needs a default-style
// status bar to match it visually
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault animated: YES];
[self presentModalViewController: picker1 animated: YES];
[picker1 release];
// [Uploads FileUpload];
}
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
[self dismissModalViewControllerAnimated: YES];
NSLog(#"%# %d",mediaItemCollection,mediaItemCollection.count);
NSArray *newMediaItem= [mediaItemCollection items];
MPMediaItem *item=[[newMediaItem objectAtIndex:0] retain];
[self uploadMusicFile:item];
}
- (void)mediaPickerDidCancel:(MPMediaPickerController *)mediaPicker
{
[self dismissModalViewControllerAnimated: YES];
NSLog(#"cancel");
}
- (void) uploadMusicFile:(MPMediaItem *)song
{
NSURL *url = [song valueForProperty: MPMediaItemPropertyAssetURL];
// Given some file path URL: NSURL *pathURL
// Note: [pathURL isFileURL] must return YES
NSString *path = [NSString stringWithFormat:#"%#",url];
NSLog(#"path %#",path);
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
NSLog(#"data %#" ,data);
NSString *audioName = #"myAudio.caf";
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.176:1001/api?type=iphoneupload"]];
[request addData:data withFileName:audioName andContentType:#"audio/caf" forKey:#"audioFile"];
[request setDelegate:self];
[request setTimeOutSeconds:500];
[request setDidFinishSelector:#selector(uploadRequestFinished:)];
[request setDidFailSelector:#selector(uploadRequestFailed:)];
[request startAsynchronous];
}
- (void)uploadRequestFinished:(ASIHTTPRequest *)request
{
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
NSData *webData = [[NSData alloc] initWithData:[request responseData]];
NSString *strEr = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"strEr %#",strEr);
}
- (void) uploadRequestFailed:(ASIHTTPRequest *)request
{
NSLog(#"responseStatusCode %i",[request responseStatusCode]);
NSLog(#"responseString %#",[request responseString]);
NSError *error = [request error];
NSLog(#"error %#",error);
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = NO;
}