RestKit parsing/Object mapping from locally stored XML - ios

I am downloading a zip, unzipping it, and then attempting to parse and object map data from an xml file included in the zip. I know if the XML file was not in a zip I could do something like
NSURL *URL = [NSURL URLWithString:#"http://restkit.org/articles"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[ responseDescriptor ]];
But because I am download a zip, I have to (or at least I think I have to) use the following code
NSURL *URL = [NSURL URLWithString:#"http://www.mediafire.com/download/6tfd33xkiepx8a3/db_UI.zip"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
self.operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"testDownload"];
self.operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
// Set download completion block
[self.operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"Successfully downloaded file to %#", path);
NSString *zipPath = path;
NSString *destinationPath = [paths objectAtIndex:0];
[SSZipArchive unzipFileAtPath:zipPath toDestination:destinationPath delegate:self];
} failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
// NSLog(#"error: %#", operation.responseString);
}];
// Start download operation
[self.operation start];
[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:#"application/xml"];
So in this case, how can I use RKObjectMapping. Or is there an alternative?.......

This is from Rest-Kit docs, This parsing JSON object if you can change the MIME Type you can do with XML and what ever
You can find it here: Rest-Kit docs
NSString* JSONString = #"{ \"name\": \"The name\", \"number\": 12345}";
NSString* MIMEType = #"application/json";
NSError* error = nil;
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:MIMEType];
id parsedData = [parser objectFromString:JSONString error:&error];
if (parsedData == nil && error) {
// Parser error...
}
RKObjectMappingProvider* mappingProvider = [RKObjectManager sharedManager].mappingProvider;
RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider];
RKObjectMappingResult* result = [mapper performMapping];
if (result) {
// Yay! Mapping finished successfully
}

Related

Save Facebook Image/URL in Parse DB

NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSString *urlString = [pictureURL absoluteString];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
// result is a dictionary with the user's Facebook data
NSDictionary *userData = (NSDictionary *)result;
NSString *facebookID = userData[#"id"];
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSString *urlString = [pictureURL absoluteString];
NSLog(#"sting=%#",urlString);
PFUser *me = [PFUser currentUser];
me[#"facebookId"] = userData[#"id"];
me["pictureURL"] = userData[urlString];
me[#"username"] = userData[#"name"];
[me saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
if (error) {
NSLog(#"Error to store=%#",error.localizedDescription);
}
}];
[self presentViewController:push animated:YES completion:nil];
} else {
[self presentViewController:push animated:YES completion:nil];
}
}];
I need to store the Facebook Image or URL when any new user login into my app. AFAIK we can't save the url directly so tried to convert it into NSString but then it threw error "'Can't use nil for keys or values on PFObject. Use NSNull for values.'"
Is there any way so that I can store that link or any other alternate way to save directly the Image into Parse?
Your issue is most likely being caused by the following line:
me["pictureURL"] = userData[urlString];
You most likely want this to be:
me["pictureURL"] = urlString;
As you have it, you will setting me[#"pictureURL"] to nil because you probably don't have a value in userData with a key matching urlString.
Try this, the url should be converted to data then saved as a PFFile.
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture? type=large&return_ssl_resources=1", facebookID]];
NSData *data = [NSData contentsOfURL:picureURL];
PFFile *file = [PFFile fileWithData:data];
//save it
[file saveInBackground];
Hope that helps!

Display Direction using google api in ios get

In Below code run so i get a response from url but when i try to get encodedPoints it give me a null value. also i update RegexKitLite but prob. not solve. Any suggestion are welcome Thank you advance.
NSString* saddr = [NSString stringWithFormat:#"%f,%f", f.latitude, f.longitude];
NSString* daddr = [NSString stringWithFormat:#"%f,%f", t.latitude, t.longitude];
NSString* apiUrlStr = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%#&sensor=false", saddr, daddr];
// http://maps.googleapis.com/maps/api/directions/json?origin=41.029598,28.972985&destination=41.033586,28.984546&sensor=false%EF%BB%BF%EF%BB%BF
NSURL *apiUrl = [NSURL URLWithString:[apiUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSLog(#"api url: %#", apiUrl);
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:nil error:nil];
NSString* encodedPoints = [apiResponse stringByMatching:#"points:\\\"([^\\\"]*)\\\"" capture:1L];
NSLog(#"encodedPoints: %#", encodedPoints);
if (encodedPoints) {
return [self decodePolyLine:[encodedPoints mutableCopy]];
}
else {
return NO;
}
I think its not a good way to do API request synchronously, especially when user' phone has poor internet connection, it will slow down the responsiveness of your application. So you should do an asynchronous API request with NSURLSession.
Also, the Directions API might return more than one routes for your request. So its better to use a NSArray to store your polyline points.
Sample code:
- (void)getPolyline {
NSURL *url = [[NSURL alloc] initWithString:#"https://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&key=YOUR_API_KEY"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithRequest:request completionHandler:
^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSError *jsonError;
NSDictionary *dict = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:data options:nil error:&jsonError];
if (!jsonError) {
NSArray *routesArray = (NSArray*)dict[#"routes"];
NSMutableArray *points = [NSMutableArray array];
for (NSDictionary *route in routesArray) {
NSDictionary *overviewPolyline = route[#"overview_polyline"];
[points addObject:overviewPolyline[#"points"]];
}
NSLog(#"%#", points);
}
} else {
//print error message
NSLog(#"%#", [error localizedDescription]);
}
}] resume];
}

How to prevent download with same request from AFHTTPRequestOperation?multiple download occurs for same file

I am using AFHTTPRequestOperation to download a file from remote server now my problem is AFHTTPRequestOperation starts to download same request multiple time so i want to prevent the download process to execute for same request.
so basically what i want is however if downloadFile: function call multiple time with same request i can prevent the download process to start if any process running with same request already.
following is my code
AFHTTPRequestOperation *operation;
-(void)downloadFile:(NSURL *)videoUrl{
NSURLRequest *request = [NSURLRequest requestWithURL:videoUrl];
operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:VIDEO_DIRECTORY_NAME];
NSString *downloadPath = [dataPath stringByAppendingPathComponent:[NSString stringWithFormat:#"TEMP_%#",[videoUrl lastPathComponent]]];
NSString *fullPath = [dataPath stringByAppendingPathComponent:[videoUrl lastPathComponent]];
// NSLog(#"Full Path For Download Video %#",fullPath);
NSError *error=[[NSError alloc]init];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullPath];
if (!fileExists)
{
NSLog(#"Full Path For Download Video Started%#",fullPath);
[operation setOutputStream:[NSOutputStream outputStreamToFileAtPath:downloadPath append:NO]];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
// NSLog(#"bytesRead: %lu, totalBytesRead: %lld, totalBytesExpectedToRead: %lld", (unsigned long)bytesRead, totalBytesRead, totalBytesExpectedToRead);
}];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
if (error) {
NSLog(#"ERR: %#", [error description]);
} else {
CustomAlertView *alert=[[CustomAlertView alloc]init];
NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
//check for Available Space
if([ALDisk freeDiskSpaceInBytes] >= [operation.response expectedContentLength])
{
NSLog(#"Content-lent: %lld", [operation.response expectedContentLength]);
[alert ShowNotificationInParentView:nil WithTitle:NSLocalizedString(#"Video_title", nil) Message:NSLocalizedString(#"Video_downloaded_succesfully", nil) IsSuperUser:[userDefaults boolForKey:IS_SUPER_USER] TypeOfNotification:ALERT_TYPE_ERROR IsLoggedIn:YES];
[assetManager.assetManagerDelegate didAssetManagerSucceedObject:nil ErrorCode:#"" Result:YES ResponseId:VIDEO_DOWNLOAD_RESPONSE_ID];
}
else {
[alert ShowNotificationInParentView:nil WithTitle:#"Memory Full" Message:NSLocalizedString(#"video_cannot_be_downloaded", nil) IsSuperUser:[userDefaults boolForKey:IS_SUPER_USER] TypeOfNotification:ALERT_TYPE_ERROR IsLoggedIn:YES];
[assetManager.assetManagerDelegate didAssetManagerFailedResponseWithError:[NSError errorWithDomain:#"Memory Full" code:[MEMORY_OUT_OF_STORAGE intValue] userInfo:nil]];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"ERR: %#", [error description]);
[assetManager.assetManagerDelegate didAssetManagerFailedResponseWithError:error];
}];
[operation start];
}
}
Please guide me with any suggestion or solution.

Couldn't download from url in my app with AFNetwotking

Im noob in AFNetworking and I learning it now. I want download file from url and save in my app (Document Folder) but it dosen't work.I have one button that when click it start download.
this is my code for download file :
- (IBAction)downloads:(id)sender
{
NSLog(#"start downloads");
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.1.100/mamal/filemanager.php"]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:[path stringByAppendingPathComponent:#"filemanager.php"] append:NO];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successfully downloaded file to %#", path);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
in this code when click on button take me this massage = 'start downloads' but dont show me 'Successfully downloaded file to %#' why?? my code not complete???
You didn't start the operation. Use the following line to start the operation :
[operation start];

How to download file using asynchronous request?

Now, when my app detect that file was updated on server, it download file and user interface stuck for downloading time. I have ASIHTTPRequest wrapper in my app, but I doesn't know how to change my download request to asynchronous.
My code:
- (void)downloadFileIfUpdated
{
NSString *urlString = #"http://www.mysite.com/data.plist";
NSLog(#"Downloading HTTP header from: %#", urlString);
NSURL *url = [NSURL URLWithString:urlString];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachedPath = [[documentPaths lastObject] stringByAppendingPathComponent:#"data.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL downloadFromServer = NO;
NSString *lastModifiedString = nil;
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error: NULL];
if ([response respondsToSelector:#selector(allHeaderFields)]) {
lastModifiedString = [[response allHeaderFields] objectForKey:#"Last-Modified"];
}
NSDate *lastModifiedServer = nil;
#try {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
df.dateFormat = #"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
df.locale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_US"];
df.timeZone = [NSTimeZone timeZoneWithAbbreviation:#"GMT"];
lastModifiedServer = [df dateFromString:lastModifiedString];
}
#catch (NSException * e) {
NSLog(#"Error parsing last modified date: %# - %#", lastModifiedString, [e description]);
}
NSLog(#"lastModifiedServer: %#", lastModifiedServer);
NSDate *lastModifiedLocal = nil;
if ([fileManager fileExistsAtPath:cachedPath]) {
NSError *error = nil;
NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:cachedPath error:&error];
if (error) {
NSLog(#"Error reading file attributes for: %# - %#", cachedPath, [error localizedDescription]);
}
lastModifiedLocal = [fileAttributes fileModificationDate];
NSLog(#"lastModifiedLocal : %#", lastModifiedLocal);
[activityIndicator stopAnimating];
}
// Download file from server if we don't have a local file
if (!lastModifiedLocal) {
downloadFromServer = YES;
}
// Download file from server if the server modified timestamp is later than the local modified timestamp
if ([lastModifiedLocal laterDate:lastModifiedServer] == lastModifiedServer) {
[activityIndicator startAnimating];
downloadFromServer = YES;
}
if (downloadFromServer) {
NSLog(#"Downloading new file from server");
NSData *data = [NSData dataWithContentsOfURL:url];
if (data) {
// Save the data
if ([data writeToFile:cachedPath atomically:YES]) {
NSLog(#"Downloaded file saved to: %#", cachedPath);
}
// Set the file modification date to the timestamp from the server
if (lastModifiedServer) {
NSDictionary *fileAttributes = [NSDictionary dictionaryWithObject:lastModifiedServer forKey:NSFileModificationDate];
NSError *error = nil;
if ([fileManager setAttributes:fileAttributes ofItemAtPath:cachedPath error:&error]) {
NSLog(#"File modification date updated");
[NSThread detachNewThreadSelector:#selector(loadPList) toTarget:self withObject:nil];
[activityIndicator stopAnimating];
}
if (error) {
NSLog(#"Error setting file attributes for: %# - %#", cachedPath, [error localizedDescription]);
}
}
}
}
}
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com"];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
// Use when fetching text data
NSString *responseString = [request responseString];
// Use when fetching binary data
NSData *responseData = [request responseData];
}];
[request setFailedBlock:^{
NSError *error = [request error];
}];
[request startAsynchronous];
For more details look at http://allseeing-i.com/ASIHTTPRequest/How-to-use#using_blocks

Resources