I'm doing a shop part for iOS application which has two page (first page for show list of voicePack in shop and second page for show detail of voice inside of voicePack).
when click on any cell in the voicePackList go to next page and in next page exists one button with name : DOWNLOAD that I want when I click on that button the voice downloaded and saved in document folder. this is the code that I made inside the button pressed processing:
- (void)downloadingVoice {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"Starting Download ...");
NSString *downloadUrl = #"10.3.1.228:9000/files";
NSURL *url = [NSURL URLWithString:downloadUrl];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if (urlData) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *voiceDirectory = [paths objectAtIndex:0];
NSString *voicePaths = [NSString stringWithFormat:#"%#%#", voiceDirectory,#"voice.mp3"];
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:voicePaths atomically:YES];
NSLog(#"Saved voice files");
});
}
});
}
- (void)btnDownloadClicked:(id)sender {
NSLog(#"Downloading Voice . . .");
[self downloadingVoice];
}
and here are how I put the button below the list of voices:
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
return 60.0f;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
// if(tableView == self.shopTableView) {
UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
UIButton *download = [UIButton buttonWithType:UIButtonTypeCustom];
[download setTitle:#"Download" forState:UIControlStateNormal];
[download addTarget:self action:#selector(btnDownloadClicked:) forControlEvents:UIControlEventTouchUpInside];
[download setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
download.frame = CGRectMake(0, 0, 130, 30);
[footerView addSubview:download];
return footerView;
}
when I click the button and put some breakpoints, it's end after if (urlData) when I check the urlData and downloadUrl, it says:
2015-09-17 10:53:01.926 Selfie[87197:674517] Starting Download ...
(lldb) po urlData
error: Couldn't materialize: couldn't get the value of variable urlData: no location, value may have been optimized out
Errored out in Execute, couldn't PrepareToExecuteJITExpression
(lldb) po downloadUrl
error: Couldn't materialize: couldn't get the value of variable downloadUrl: variable not available
Errored out in Execute, couldn't PrepareToExecuteJITExpression
anyone please help me to solve this.. I'll be really thank you for your help..
First of all, you are fetching voice data synchronously which is not advisable as this hangs your main thread. You can use your main thread to show the loading overlay and allow user to cancel the download operation if it is taking too much of time. Please use below method to make an Asynchronous call rather.
Secondly, can you please ensure the URL you are pointing to is open on the network you are trying to access the files. If this is a local server, better put localhost rather than IP address.
- (void)fetchFilesAsynchronously {
NSURL *myUrl = [NSURL URLWithString:#"http://10.3.1.228:9000/files"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:myUrl cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0];
// Add headers as per your need
[urlRequest setValue:#"value" forHTTPHeaderField:#"key"];
// Add body as per your need
NSDictionary *body = #{#"key" : #"value"};
NSData *requestBodyData = [NSJSONSerialization dataWithJSONObject:body options:NSJSONWritingPrettyPrinted error:nil];
[urlRequest setHTTPBody:requestBodyData];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *iResponse, NSData *iData, NSError *iConnectionError) {
// Handle response here
}];
}
Third, for your debugger issue, please take a look at this thread.
Related
I'm attempting to write a SplitView control program in which pressing a table cell in the masterViewController causes an associated web page to load in the detail view controller. I have the following method in the detail view controller that I can confirm is getting called and is receiving the correct input:
-(void)masterAction:(id)sender {
NSString *http = #"http://";
http = [http stringByAppendingString:sender];
_urlString = http;
NSURL *url= [NSURL URLWithString:_urlString];
[self.web loadRequest:[NSURLRequest requestWithURL:url]];
}
However, nothing is loading. Any ideas why this might be? The only way I've been able to get anything at all to load is to insert something similar to the following in my viewDidLoad method:
NSURL *url= [NSURL URLWithString:#"http://www.google.com];
[self.web loadRequest:[NSURLRequest requestWithURL:url]];
The method is being called using:
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *thread = [self.issueData objectForKey:#"responseData"];
NSDictionary *feed = [thread objectForKey:#"feed"];
NSArray *entries = [feed objectForKey:#"entries"];
NSDictionary *posts = entries[indexPath.row];
NSString *urlString = [posts objectForKey:#"link"];
NSArray *split = [urlString componentsSeparatedByString:#"url=http://"];
NSString *url = [split objectAtIndex:1];
[self.delegate masterAction:url];
}
set the delegate of webview.
and try this.
NSString *myUrl = #"http://www.YourWebSite.com";
NSURL *webUrl = [NSURL URLWithString:myUrl];
[webObj loadRequest:[NSURLRequest requestWithURL:webUrl]];
I duplicated this code in a test project and the only piece of code where something can go wrong is if you are forgetting to put www. after the http:// before the domain name.
Trying changing your masterAction method to the one below:
- (void) masterAction: (id) sender
{
if (![sender isKindOfClass:[NSString class]]) return;
NSString *http = #"http://www.";
NSString *urlString = [http stringByAppendingString:sender];
NSURL *url = [NSURL URLWithString:urlString];
[self.web loadRequest:[NSURLRequest requestWithURL:url]];
}
If this is not the issue and the string being sent to the method contains the www. try setting the delegate of the UIWebView to see if any error is thrown when loading the request.
I have UITableView with UIWebView in it.
Before I load UITableView, I fetch some JSON on another thread
-(void)fetchJson
{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSString* url = ...
NSData* theData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
#try {
NSError *error;
NSMutableArray* json = [NSJSONSerialization
JSONObjectWithData:theData
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
if (error){
NSLog(#"%#",[error localizedDescription]);
NSLog(#"if");
}
else{
...
// here I fetch a string which holdshtml and MathML data in it.
NSString *eq_text = [question objectForKey:#"eq_text"];
stq.question = eq_text;
...
}
}
#catch (NSException *exception) {
NSLog(#"Exception");
}
dispatch_async(dispatch_get_main_queue(), ^{
_counter = _questionsArray.count;
[_tableView reloadData];
});
});
This is how I loadRequest to WebView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
[cell.webView loadRequest:[self readMathMlString:question.question]];
...
return cell;
}
With method [self readMathMlString:eq_text] I make NSUrlRequest. I have some MathJax That I need to show in the WebView, And I have to show it this way
-(NSURLRequest*)readMathMlString:(NSString*)content{
NSString *tmpFileName = #"test1.html";
//temp dir
NSString *tempDir = NSTemporaryDirectory();
//create NSURL
NSString *path4 = [tempDir stringByAppendingPathComponent:tmpFileName];
NSURL* url = [NSURL fileURLWithPath:path4];
//setup HTML file contents
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"MathJax" ofType:#"js" inDirectory:#"MathJax-2.2-latest"];
//write to temp file "tempDir/tmpFileName", set MathJax JavaScript to use "filePath" as directory, add "xContent" as content of HTML file
[self writeStringToFile:tempDir fileName:tmpFileName pathName:filePath content:content];
NSURLRequest* req = [[NSURLRequest alloc] initWithURL:url];
//original request to show MathJax stuffs
//[myWebView loadRequest:req];
return req;
}
So, the problem is, for some reason data is shown in the strange order.
When the View is open for the first time, app shows first 4 cells appearing absolutely same, but they shouldn't be.
See example below:
This is the screenshot of what is shown:
This is NSLog of data that should be show
From here, we can see that for some reason, it displays all 4 cells with the data from what should be the 3rd cell.
Also, when i scroll my table view down and then up again, the data in WebView changes again.
Example:
What could be the cause of all this and how to solve it?
I'm still learning iOS , just i finish my first application but i want to add some function when the application running , here I'm using did finish launching with option method in appdelegate , i want to change this code , first check if the user have internet or not if not show uialertView also , if there is no internet i need a function can stop the application like
Alert ( this application need internet and you dont have internet right now pls try later ) and the application will exit .
or also in some case maybe the web service out of work
if possible explain me where i should put the if statement and how i can exit the application
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[UINavigationBar appearance] setBarTintColor:[UIColor lightGrayColor]];
NSFileManager *fileManger=[NSFileManager defaultManager];
NSError *error;
NSArray *pathsArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *doumentDirectoryPath=[pathsArray objectAtIndex:0];
NSString *destinationPath= [doumentDirectoryPath stringByAppendingPathComponent:#"istudentDatabase.plist"];
// NSLog(#"plist path %#",destinationPath);
//if Plist not exists will copy new one
if ([fileManger fileExistsAtPath:destinationPath]){
NSLog(#"Settings File exists ");
}else{
// Copy New Plist
NSString *sourcePath=[[[NSBundle mainBundle] resourcePath]stringByAppendingPathComponent:#"istudentDatabase.plist"];
[fileManger copyItemAtPath:sourcePath toPath:destinationPath error:&error];
}
settingsClass * settings =[[settingsClass alloc]init];
NSNumber * userid = [settings loadPlist:[NSString stringWithFormat:#"userid"]];
if ([userid intValue] == 0)
{
//NSLog(#"You Dont Have USerid ");
// Send a synchronous request
NSURLRequest * urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://fahads-macbook-pro.local/ios/newuser.php"]];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
if (error == nil)
{
NSDictionary * mydata = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[settings saveNewUserId:[mydata[#"userid"] intValue]];
NSLog(#"%#",mydata[#"userid"]);
}else{
NSLog(#"Error please Check Your Connections ");
}
}else{
NSLog(#"You Have Userid : %#",userid);
}
NSMutableDictionary * itemsPlist = [[NSMutableDictionary alloc]initWithContentsOfFile:destinationPath];
NSLog(#"Items : %#",itemsPlist);
return YES;
}
also if there is no way to exit the application , i have view controller and on this view controller there is push button i want to hide this button from appdelegate with If statement for example if no connection hide the start button and show some hint there is no connection.
thanks advance
In my application i am using Uiwebview for displaying vimeo authorization page, after the user has authorized it, i have to parse the url for OAtoken and dismiss it, for that i am using should startLoad delegate method, but after the process is over and when i am returning NO, the control is not transferred back...
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSURL *url = [request mainDocumentURL];
NSString *str1 = [url absoluteString];
NSString *str = #"https://vimeo.com/oauth/confirmed";
//[webView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"bg_cork.png"]]];
if([str isEqualToString:str1])
{
//removing the webview after the user approves.
//[webView removeFromSuperview];
return YES;
}
//parsing the redirected url to get the oauth_verifier.
URLParser *parser = [[URLParser alloc] initWithURLString:str1];
Oauth_verifier = [parser valueForVariable:#"oauth_verifier"];
//getting the final access token by giving the oauth verifier.
NSURL *url_access = [[NSURL alloc] initWithString:#"https://vimeo.com/oauth/access_token"];
OAMutableURLRequest *reques_access = [[OAMutableURLRequest alloc]initWithURL:url_access consumer:consumer token:acessToken realm:nil signatureProvider:nil];
OARequestParameter *p2 = [[OARequestParameter alloc] initWithName:#"oauth_verifier" value:Oauth_verifier];
NSArray *params2 = [NSArray arrayWithObject:p2];
[reques_access setParameters:params2];
[reques_access setHTTPMethod:#"GET"];
OADataFetcher *fetcher_access = [[OADataFetcher alloc]init];
[fetcher_access fetchDataWithRequest:reques_access delegate:self didFinishSelector:#selector(acessTokenTicket:didFinishWithData:) didFailSelector:#selector(acessTokenTicket:didFailWithError:)];
//if the access token is successfully generated then the control transferrd to acessTokenTicket did finish with data
// Return YES if you want to load the page, and NO if you don't.
NSLog(#"at return yes");
if (i==1) {
NSLog(#"returning no");
[webView removeFromSuperview];
return NO;
}
return YES;
}
i am sure that it is going to return no because the statement "returning no" is printed, but the control is not returned,i have given the statement
NSLog(#"returned from web view delegate");
in the main function to know whether the control is returned it is not returned and also the operations below are not performed.
I am trying to load data from web with few simple steps:
NSData *JSONData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:#"******"]];
NSObject *json = [JSONData objectFromJSONData];
NSArray *arrayOfStreams = [json valueForKeyPath:#"programs"];
NSDictionary *stream = [arrayOfStreams objectAtIndex:0];
NSString *str = [[NSString alloc]initWithString:[stream valueForKey:#"image"]];
NSURL *urlForImage1 = [NSURL URLWithString:str];
NSData *imageData1 = [NSData dataWithContentsOfURL:urlForImage1];
_screenForVideo1.image = [UIImage imageWithData:imageData1];
But the problem is I am doing 30 of this right after my application launches...
I want to load about 5 of them, and than load others. Because when I try to load all of them at the same time, my app is not launching all of them loaded...
Is there any way that I can load first few of them, and wait, and than load others?
As for loading them, you should probably display a spinner, start loading the image in background and then replace the spinner with the image once it’s ready.
- (void) viewDidLoad {
UIActivityIndicator *spinner = …;
[self.view addSubview:spinner];
[self performSelectorInBackground:#selector(startLoadingImage)
withObject:nil];
}
- (void) startLoadingImage {
// You need an autorelease pool since you are running
// in a different thread now.
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
UIImage *image = [UIImage imageNamed:#"foo"];
// All GUI updates have to be done from the main thread.
// We wait for the call to finish so that the pool won’t
// claim the image before imageDidFinishLoading: finishes.
[self performSelectorOnMainThread:#selector(imageDidFinishLoading:)
withObject:image waitUntilDone:YES];
[pool drain];
}
- (void) imageDidFinishLoading: (UIImage*) image {
// fade spinner out
// create UIImageView and fade in
}