IOS progress dialog - ios

I want to convert an android app to iPhone. I managed to get the contents of a server by,
NSString *s =[NSString stringWithFormat:#"www.xyz.com"];
NSURL *url = [NSURL URLWithString:s];
// NSLog(s);
NSString *content = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:nil];
NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
But, how to get the progress dialog with rotating spinner till it loads. Kindly help and oblige.

MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeAnnularDeterminate;
hud.labelText = #"Loading";
[self doSomethingInBackgroundWithProgressCallback:^(float progress) {
hud.progress = progress;
} completionCallback:^{
[hud hide:YES];
}];
you have add this code
download source from https://github.com/jdg/MBProgressHUD

Related

Convert Music File to NSData using MPMediaPickerController

I am using MPMediaPickerController to upload music files. When I tried to convert MPMediaItem to NSData, the NSData always returns NULL.
Here is my code:
- (IBAction)addMusic:(id)sender {
MPMediaPickerController *soundPicker=[[MPMediaPickerController alloc] initWithMediaTypes:MPMediaTypeMusic];
soundPicker.delegate=self;
soundPicker.allowsPickingMultipleItems=NO;
[self presentViewController:soundPicker animated:YES completion:nil];
}
- (void)mediaPicker: (MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection{
MPMediaItem *item = [[mediaItemCollection items] objectAtIndex:0];
NSURL *url = [item valueForProperty: MPMediaItemPropertyAssetURL];
NSString *audioFilePath = [NSString stringWithFormat:#"%#",url];
NSData *audioData = [NSData dataWithContentsOfFile:audioFilePath];
[self dismissViewControllerAnimated:YES completion:nil];
}
Please suggest what can I do to convert MPMediaItem to NSData.
Your problem is in these three lines:
NSURL *url = [item valueForProperty: MPMediaItemPropertyAssetURL];
NSString *audioFilePath = [NSString stringWithFormat:#"%#",url];
NSData *audioData = [NSData dataWithContentsOfFile:audioFilePath];
Try doing:
NSURL *url = [item valueForProperty: MPMediaItemPropertyAssetURL];
NSError *error = nil;
NSData *audioData = [NSData dataWithContentsOfURL:url options:nil error:&error];
if(!audioData)
NSLog(#"error while reading from %# - %#", [url absoluteString], [error localizedDescription]);
And see if that works better.
If you're interested, what was wrong with the first block of code there was that [NSString stringWithFormat:#"%#",url] probably gives a nil result, since url is a NSURL object and NSString's format is expecting a NSString object.

uidocumentinteractioncontroller sending file URL besides image in Viber

I am using a standard UIDocumentInteractionController in my app, and provide it with a local image URL.
However, once Viber is selected, it first sends a plain text message with the file URL and then the image. I only want to send the image ofcourse.
I see that it's working allright from the native Gallery, so it's obviously my fault.
here's the code:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString* path = [docs stringByAppendingFormat:#"/tempName.jpg"];
MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:imgPicker.view];
HUD.mode = MBProgressHUDModeAnnularDeterminate;
[imgPicker.view addSubview:HUD];
[HUD show:YES];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, 80)];
NSError *writeError = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&writeError];
_documentInteractionController = [UIDocumentInteractionController interactionControllerWithURL:[NSURL URLWithString:path]];
[_documentInteractionController setUTI:(NSString *)kUTTypeJPEG];
_documentInteractionController.delegate = self;
dispatch_async(dispatch_get_main_queue(), ^{
//Your main thread code goes in here
[HUD removeFromSuperview];
[_documentInteractionController presentOptionsMenuFromRect:CGRectZero inView:imgPicker.view animated:YES]; });
});

How to get the values from json service [duplicate]

This question already has an answer here:
Parsing JSON response .
(1 answer)
Closed 8 years ago.
Hai I need to get the id & status from the service for login my code is below. please guide me to get the values.. Thanks in advance..
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.xxx/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSData *data=[NSData dataWithContentsOfURL:url];
1st Do the jSon parsing and then get the particular value from the
key .
Before getting any value , we have to understand the tree of jSon.
Here "posts" is an NSArray ,within that one DIctionary "post" is
there ,which again contains another dictionary.
Below is the complete code.
(void)viewDidLoad
{
[super viewDidLoad];
 NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link =
[NSString stringWithFormat:#"http://www.some.com/webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
}); }
Then call that selector fetchedData
(void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
 
if(!error){
NSArray* postArray = [json objectForKey:#“posts”]; //This is an array
if (postArray.count>0) {
NSDictionary *dict = [[postArray objectAtIndex:0] objectForKey:#"post" ];
NSString *id_ = [dict objectForKey:#"id"];
NSString *status_ = [dict objectForKey:#"status"];
}
}
}
Can you post your json string. You can use NSJSONSERIALISATION to convert data (json string ) into NSDictionary. Then use the keys to extract the values. I'm replying through mobile so I can't write the actual code.
Use Below code to parse Json in IOS
NSString *Username= txtUsername.text;
NSString *Password=txtPassword.text;
NSString *link = [NSString stringWithFormat:#"http://www.some.com/_webservice/login.php?user=%#&pass=%#&format=json",Username,Password];
NSURL *url=[NSURL URLWithString:link];
NSMutableURLRequest *req1 = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *response;
NSError *error;
//getting the data
NSData *newData = [NSURLConnection sendSynchronousRequest:req1 returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:newData encoding:NSUTF8StringEncoding];
NSLog(#"basavaraj \n\n\n %# \n\n\n",responseString);
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
NSString *id=[res objectForKey:#"ID"];
NSString *status=[res objectForKey:#"Status"];
and if u need extra info please go through below link it may help you
Click here for more details

Image URL JSON parse to UIImageView in app error

I'm trying to parse an image url through JSON in my iPhone application.
My json model is built like this:
{
"picture":"link_to_image.jpg",
"about":"about text here",
"name":"Name"
}
I use this code to parse the itemw in my app:
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&error];
self.titleLabel.text = [json objectForKey:#"name"];
self.aboutText.text = [json objectForKey:#"about"];
self.profileImage.image = [json objectForKey:#"picture"];
}
And in ViewDidLoad I wrote this:
dispatch_queue_t queue = dispatch_get_global_queue
(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"link_to_my_json_file.php"]];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
I've connected the outlets to the items in my .xib-file and the title and about text are successfully parsed to the label and textview. But the image won't parse. The app keeps crashing when I try this for the image.
Can someone please explain what I'm doing wrong?
Thanks!
As #Hot Licks have mentioned in comments you are putting a NSString pointer into UIImage property. Following method should work.
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions error:&error];
self.titleLabel.text = [json objectForKey:#"name"];
self.aboutText.text = [json objectForKey:#"about"];
NSURL *URL = [NSURL URLWithString: [json objectForKey:#"picture"]];
dispatch_queue_t queue = dispatch_get_global_queue
(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSData *data = [NSData dataWithContentsOfURL: URL];
self.profileImage.image = [UIImage imageWithData: data];
});
}

Background thread confusion

I'm trying to improve the responsiveness of my app but am a complete newbie to threading and have become confused.
On launch an alert is shown:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0)
{
NSString *user = [[alertView textFieldAtIndex:0] text];
NSString *pass = [[alertView textFieldAtIndex:1] text];
[self loginToServerWithUsername:user andPassword:pass];
}
}
within the loginToServerWithUsername: method, the app calls a method:
[self checkFiles:sessionID];
This can take several seconds so I tried to execute it in the background:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self checkFiles:sessionID];
});
checkFiles method:
fileList = [[NSMutableString alloc] init];
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directoryPaths objectAtIndex:0];
NSString *downloadsFolderString = [documentsDirectory stringByAppendingPathComponent:DOWNLOADS_FOLDER];
NSError *error = nil;
NSString* file;
NSDirectoryEnumerator* enumerator = [[NSFileManager defaultManager] enumeratorAtPath:downloadsFolderString];
while (file = [enumerator nextObject])
{
BOOL isDirectory = NO;
[[NSFileManager defaultManager] fileExistsAtPath: [NSString stringWithFormat:#"%#/%#",downloadsFolderString,file]
isDirectory: &isDirectory];
if (!isDirectory)
{
[fileList appendString:[NSString stringWithFormat:#"%#|", file]];
}
}
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd/MM/yyyy HH:mm"];
NSString *timeOpened = [formatter stringFromDate:[NSDate date]];
NSString *post = [NSString stringWithFormat:#"sessionID=%#&fileList=%#&dateTime=%#&userID=%#", sessionID, fileList, timeOpened, userID];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSString *comparisonURLString = SERVER_COMPARE_URL_STRING;
NSURL *comparisonURL = [NSURL URLWithString:comparisonURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:comparisonURL];
[request setHTTPMethod:#"POST"];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
NSHTTPURLResponse *urlResponse = nil;
error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
if (responseData)
{
NSString *requiredFilesList = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSArray *lines = [requiredFilesList componentsSeparatedByString: #"\n"];
if (lines.count > 2)
{
dispatch_async(dispatch_get_main_queue(), ^(void){
NSRange theRange;
theRange.location = 2;
theRange.length = [lines count] -3;
numberOfFilesToBeDownloaded = theRange.length;
if (numberOfFilesToBeDownloaded <= 0)
{
_jobStatusLabel.text = #"Documents up to date"; // is this the issue?
}
if (numberOfFilesToBeDownloaded > 0)
{
NSArray *subArray = [lines subarrayWithRange:theRange];
[self animateProgressBar];
if (![eraseDevice isEqualToString:#"true"])
{
[self getFiles:subArray];
}
}
});
}
}
else
{
NSLog(#"no response data from check files");
}
However, the alertView is not dismissed until the checkFiles method is complete.
Can anyone tell me how to have the alert dismiss whilst checkFiles runs in the background?
The UI operations should be done in the main thread.
For instance :
_jobStatusLabel.text = #"Documents up to date"; // is this the issue?
should be
dispatch_async(dispatch_get_main_queue(), ^(void){
_jobStatusLabel.text = #"Documents up to date"; // is this the issue?
});
change all such possible cases.
Obviously you are updaing UI elemets from background thread. This would lead to unpredictable behavior. A better way to do this is like this -
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
[self checkFiles:sessionID];
dispatch_async(dispatch_get_main_queue(),^{
//breakup your checkFiles method to background tasks & UI tasks. Put UI updating
//code here which will get executed in the main thread.
});
});
This is the GCD pattern of coding. Here it is asynchronous thread executes code synchronously. i.e. after checkFiles finishes the next code (here its a async thread) gets executed.
You would need to break checkFiles method. Execute the HTTP part in the background thread and pass the parsed responseData to main UI thread. After that update the UI. See if this works...

Resources