obj-c return block NSString to c++ after request - c++

I'm trying to get this data correctly back to c++, but there are some random crashes. I want to access the data in C++. Sometimes it does, sometime it doesn't. I couldn't find a clear example on how to return this data. Here's my code:
- (NSString*) sendRequestToServer : (CLLocationCoordinate2D) location {
NSLog(#"getting geo from server %# %# ", [NSString stringWithFormat:#"%f", location.latitude],[NSString stringWithFormat:#"%f", location.longitude]);
__block long returnBytesSend = 0;
__block long returnBytesTotal = 0;
__block NSString* tempData = #"" ;
__block BOOL foundNow = false;
self.data = nil;
for (NXOAuth2Account *account in [[NXOAuth2AccountStore sharedStore] accounts]) {
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject: [NSString stringWithFormat:#"%f", location.latitude] forKey: #"latitude"];
[params setObject: [NSString stringWithFormat:#"%f", location.longitude] forKey:#"longitude" ];
[params setObject: #"10" forKey: #"radius" ];
[params setObject: #"5" forKey: #"limit"];
NXOAuth2Client *client = [account oauthClient];
NXOAuth2AccessToken *tokenData = [client accessToken];
NSString * clientAccessToken = [tokenData accessToken];
NSString * clientRefreshToken = [tokenData refreshToken];
if (clientAccessToken && clientRefreshToken ){
[NXOAuth2Request performMethod:#"GET"
onResource:[NSURL URLWithString:#"http://www.server.com/list"]
usingParameters: params
withAccount:account
sendProgressHandler:^(unsigned long long bytesSend, unsigned long long bytesTotal) {
returnBytesSend = bytesSend ;
returnBytesTotal = bytesTotal;
}
responseHandler:^(NSURLResponse *response, NSData *responseData2, NSError *error){
NSLog(#"FOUND DATA");
NSRange range = [[[NSString alloc] initWithData:responseData2 encoding:NSUTF8StringEncoding] rangeOfString : #"facebook_id"];
if(range.location != NSNotFound) {
tempData = [[[NSString alloc] initWithData:responseData2 encoding:NSUTF8StringEncoding]retain];
//NSLog(#"%#", tempData);
self.data = [[tempData copy] autorelease];
foundData = true;
}
}];
}
}
return tempData;
}
I was trying to acces the data this way:
#interface oAuthView : UIWebView
#property (nonatomic, strong) __block NSString* data;
#property (nonatomic) __block BOOL foundData;
and in c++ like this:
oAuthView *getWebView;
getWebView =[[oAuthView alloc] initWithFrame:CGRectMake(10,40,300,400)];
if ([getWebView foundData] )
string dataS = string([[artPartView data] UTF8String]));

Related

PHImageManager.default().requestAVAsset for video

i have an big problem with my situation
my main problem is i need fetch video one by one do some operation on the video name and save it to the file system and again fetch another video do some operation on the video name and save it to the file system through the loop of asset the problem is completion handler prevent me do that because it saving all videos together without i do any editing and changing the name this save all videos i think it is working on background thread please any help to fix this problem i need handle fetch video one by one
this is my code
for asset in arrayOfAssets {
if asset.mediaType == .video {
PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (AVAsset, AVAudio, info) in
// i need access to this place so i can fetch the video one by one and working with the AVAsset
})
}else{
let imageOp = PHImageRequestOptions()
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width:125,height:125), contentMode: .aspectFit, options: imageOp, resultHandler: { (img, info) in
print(img!)
})
}
}
i think this one is related to your query
for Vedios
How Can i Get the List of all Video files from Library in ios sdk
for Images
Get all of the pictures from an iPhone photoLibrary in an array using AssetsLibrary framework?
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[`allVideos` addObject:dic];
}
}];
else
{
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
--------for ALL PHOTOS
NSArray *imageArray;
NSMutableArray *mutableArray;
-(void)getAllPhotosFromCamera
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
requestOptions.synchronous = true;
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
NSLog(#"%d",(int)result.count);
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[result count]];
// assets contains PHAsset objects.
__block UIImage *ima;
for (PHAsset *asset in result) {
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[images addObject:ima];
}];
}
imageArray = [images copy]; // You can direct use NSMutuable Array images
}

Databse getting locked when trying to update and insert

When i try to insert or update, database gets locked randomly. I am giving the code that I am using. Kindly let me know if something else needs to be done apart from this.
I read some where this issue occurs because of open and close functionality of database. Please let me know what the issue is?
-(BOOL)createDB : (const char *)str {
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"SpotLogic.db"]];
BOOL isSuccess = YES;
// NSFileManager *filemgr = [NSFileManager defaultManager];
dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
char *errMsg;
const char *sql_stmt = str;
if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg)
!= SQLITE_OK)
{
isSuccess = NO;
NSLog(#"Failed to create table");
}
sqlite3_close(database);
return isSuccess;
}
else {
isSuccess = NO;
NSLog(#"Failed to open/create database");
}
return isSuccess;
}
- (BOOL)deleteData:(NSString *)deleteSql
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"SpotLogic.db"]];
dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *insert_stmt = [deleteSql UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
NSLog(#"deleted");
}
else {
NSLog(#"Not deleted");
return NO;
}
sqlite3_reset(statement);
}
return NO;
}
- (BOOL)insertData:(NSString *)insertSQL
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"SpotLogic.db"]];
dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
NSLog(#"inserted");
}
else {
NSLog(#"Not inserted");
return NO;
}
sqlite3_reset(statement);
}
return NO;
}
- (sqlite3_stmt *)fetchData:(NSString *)fetchSQL
{
NSLog(#"%#",fetchSQL);
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"SpotLogic.db"]];
// array = [[NSMutableArray alloc]init];
dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *fetch_stmt = [fetchSQL UTF8String];
if(sqlite3_prepare_v2(database, fetch_stmt,-1, &statement, NULL)==SQLITE_OK)
{
sqlite3_reset(statement);
}
else
{
}
}
return statement;
}
- (BOOL)update:(NSString *)insertSQL
{
NSString *docsDir;
NSArray *dirPaths;
// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
// Build the path to the database file
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent: #"SpotLogic.db"]];
dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &database) == SQLITE_OK)
{
const char *insert_stmt = [insertSQL UTF8String];
sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_DONE)
{
return YES;
NSLog(#"inserted");
}
else {
NSLog(#"Not inserted");
return NO;
}
sqlite3_reset(statement);
}
return NO;
}
I actually found the problem. My database gets locked when I run this code.
for(int i = 0 ; i < meeting_ids.count ; i ++){
statement = [[DataManger getSharedInstance] fetchData:[NSString stringWithFormat:#"SELECT red_flag FROM meeting_question WHERE meeting_id = '%#'",[meeting_ids objectAtIndex:i]]];
while (sqlite3_step(statement) == SQLITE_ROW)
{
char *field1=(char *) sqlite3_column_text(statement, 0);
NSString *name =[[ NSString alloc]initWithUTF8String:field1];
NSLog(#"%#",name);
if([name isEqualToString:#"1"]){
[red_flag replaceObjectAtIndex:i withObject:#"1"];
break;
}
}
}
This while with for loop is the reason.
I have to get 'red_flag' from all the meetings with meeting ids in 'meeting_ids' array.
Any other way to do this
Try this:
If you opens database every time, then close it also every time.
So, write ...
sqlite3_close(database);
this line in all function.
After running statement please use these two statement for reset and finalize statement then close data base.
sqlite3_reset(statement);
sqlite3_finalize(statement);
sqlite3_close(database);

Is there a quick way to POST an NSDictionary to a Python/Django server?

I'm looking to send an NSDictionary up to a server running Django, and I would prefer if I had to do little or no work writing an encoder/parser.
Is there an easy way to accomplish this task?
iOS 5 has support for it in the framework. Look at NSJSONSerialization. Here is example code for post. Request object creation has been omitted in the code below.
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObjectsAndKeys:API_KEY, #"apiKey", userName, #"loginUserName", hashPassword, #"hashPassword", nil], #"loginReq", nil];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"content-type"];
NSError *error = nil;
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error]];
iOS doesn't have support to do this as a one-liner, but you could do this:
#interface NSString (URLEncoding)
- (NSString *)urlEncodedUTF8String;
#end
#interface NSURLRequest (DictionaryPost)
+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
parameters:(NSDictionary *)parameters;
#end
#implementation NSString (URLEncoding)
- (NSString *)urlEncodedUTF8String {
return (id)CFURLCreateStringByAddingPercentEscapes(0, (CFStringRef)self, 0,
(CFStringRef)#";/?:#&=$+{}<>,", kCFStringEncodingUTF8);
}
#end
#implementation NSURLRequest (DictionaryPost)
+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
parameters:(NSDictionary *)parameters {
NSMutableString *body = [NSMutableString string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
for (NSString *key in parameters) {
NSString *val = [parameters objectForKey:key];
if ([body length])
[body appendString:#"&"];
[body appendFormat:#"%#=%#", [[key description] urlEncodedUTF8String],
[[val description] urlEncodedUTF8String]];
}
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
return request;
}
#end
Then it's as simple as:
NSURL *url = [NSURL URLWithString:#"http://posttestserver.com/post.php"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:42], #"number",
#"apple", #"brand", nil];
NSURLRequest *request = [NSURLRequest postRequestWithURL:url parameters:params];
[NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:nil];
Please note that in this example we're not caring about the response. If you care about it, supply a block so you can do something with it.

NSArray and NSDictionary add duplicate objects

When adding objects to NSArray or NSDictionary, my app only shows a duplicate of the last entry.
I get the data and send it to the observer...
[[NSNotificationCenter defaultCenter] postNotificationName:#"xmlFinishedLoading" object:self userInfo:[NSDictionary dictionaryWithObject:currentEventObject forKey:#"notifKey"]];
This code is ran when observer receives notification...
-(void)populateCurrentEventsTableView:(NSDictionary *)events
{
NSDictionary *info = [events valueForKey:#"userInfo"];
Event *evt = [info valueForKey:#"notifKey"];
if (self.eventDictionary == nil) {
self.eventDictionary = [[NSMutableDictionary alloc]init];
}
[self.eventList addObject:evt];
NSString *key = [NSString stringWithFormat:#"%i",[eventList count] - 1];
[self.eventDictionary setValue:evt forKey:key];
NSLog(#"events description = %#",evt.eventDescription);
[self.tableView reloadData];
}
TableView reloaded with this code...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"ActivitiesList";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
NSUInteger row = [indexPath row];
NSString *rowKey = [NSString stringWithFormat:#"%i",row];
Event *evt = [eventDictionary objectForKey:rowKey];
cell.textLabel.text = evt.eventDescription;
cell.detailTextLabel.text = evt.eventSecondaryDescription;
return cell;
}
The NSLog that displays event description is fine it shows different entries as they come. However if I were to display the entries of eventDictionary, it shows same entry. Any help?
More containing code would be helpful, what you've got looks good to me. What method does this code appear in? Is it possible that self.eventDictionary is being erased each time you come back with a userInfo object to populate it with?

parse XML to NSArray of NSDictionary - error - why?

I have a problem parsing a XML to NSArray of NSDictionary. I don't know why, but instead of the array gets 2 objects (in this case), it take 2 objects with equal data... Why?
Here's the code:
#interface RLparseXMLToArrayOfDictionarys : NSObject <NSXMLParserDelegate> {
NSMutableArray *arrayWithResult;
NSMutableDictionary *tempDict;
NSMutableString *currentString;
NSString *groupKey;
}
#property (nonatomic, strong) NSString *groupKey;
#property (nonatomic, retain) NSMutableArray *arrayWithResult;
#property (nonatomic, retain) NSMutableDictionary *tempDict;
-(NSArray *)parseXMLWithStringToArray:(NSString *)stringWithXML withGroupKey:(NSString *)groupKeyToIgnore;
#end
#implementation RLparseXMLToArrayOfDictionarys
#synthesize groupKey;
#synthesize arrayWithResult;
#synthesize tempDict;
- (id)init
{
self = [super init];
if (self) {
}
return self;
}
-(NSArray *)parseXMLWithStringToArray:(NSString *)stringWithXML withGroupKey:(NSString *)groupKeyToIgnore{
NSData *currentStringData = [stringWithXML dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:currentStringData];
[parser setDelegate:self];
// Set Parser Options
[parser setShouldProcessNamespaces:NO];
[parser setShouldReportNamespacePrefixes:NO];
[parser setShouldResolveExternalEntities:NO];
//key to ignore
self.groupKey = groupKeyToIgnore;
if (!arrayWithResult) {
arrayWithResult = [[NSMutableArray alloc] init];
}
if (!tempDict) {
tempDict = [[NSMutableDictionary alloc] init];
}
[parser parse];
NSLog(#"return: %#", arrayWithResult);
return arrayWithResult;
}
#pragma mark -
#pragma mark XML methods
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if(!currentString){
currentString = [[NSMutableString alloc] init];
}
[currentString appendString:string];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
NSString *currentStringNoWhiteSpace = [currentString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if ([elementName isEqualToString:groupKey]){
[arrayWithResult addObject:tempDict];
// [tempDict removeObjectsForKeys:[tempDict allKeys]];
}
else if (currentStringNoWhiteSpace != nil)
[tempDict setValue:currentStringNoWhiteSpace forKey:elementName];
currentStringNoWhiteSpace = nil;
currentString = nil;
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
}
#end
Done!
Replace [tempDict removeObjectsForKeys:[tempDict allKeys]];
with tempDict = [[NSMutableDictionary alloc] init];
:)