I using a Core Data with 2 entities One is my archive, have reference for image, name and NSNumber the second Entity is mi numeric balance.
In the Archive view i can load Archive entity in to a UITable View, if i tap on my cell i have the perfect detail and my button to set the Card.
In the detail I've the Delete button, this have a function to delete a single card and in to Balance entity change the numeric value.
If i try to delete is working well and the Balance load good the new value, but is i add new card, my balance add a new value plus the last value erased:
Start App add my card with Name, Image and value (10), Balance show 1 card, total 10, is ok.
Go to my archive select my card and Delete, now i have empty archive, and my Balance showing 0 card and 0 value, now if i add other card exaple value 10, my balance sowing 2card and 20value.
this is the code using to delete:
- (IBAction)delete:(id)sender {
NSError *error;
NSManagedObjectContext *context = [self managedObjectContext];
[context deleteObject:loadA[_currentRecord]];
//image remover from documents folder//
NSString *imageRemover = [[self docsDir]stringByAppendingPathComponent:nomeSc.text];
[[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:#"%#.jpg", imageRemover] error:&error];
//----------------------------------//
if (![context save:&error]){
NSLog(#"Save Error, please retry: %#", [error localizedDescription]);
}
[self refreshBalance];
_currentRecord =-1;
}
- (void)refreshBalance:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
if (_currentRecord <= -1) {
modifyA = loadA[_currentRecord];
modifyB = loadB[currentBalance];
}
int oldBet = [betOld.text intValue];
int cardBetting = [modifyB.totalCards intValue];
int amauntBet = [blDetail[0] intValue];
modifyB.totBet = [NSNumber numberWithInteger:amauntBet - oldBet];
modifyB.totCards = [NSNumber numberWithInt:cardBetting -1];
}
NSError *error;
if (![context save:&error]) {
NSLog(#"Errore durante il salvataggio: %#", [error localizedDescription]);
}
_currentRecord = -1;
_currentBalance = -1;
[self.navigationController popViewControllerAnimated:YES];
}
**********THIS IS A FUNCTION TO SAVE*****************
- (IBAction)onSave:(id)sender{
NSString* documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imageName = self.name.text;
NSString* foofile = [documentsPath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg", imageName]];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile];
if (fileExists == YES){
NSString *titolo = #"Warning";
NSString *messaggio = [NSString stringWithFormat:#"Your name ( %# ) exist, please changeit!", imageName];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
} else
if (nomeGiocata.text.length == 0 || importoGiocato.text.length == 0 ) {
NSString *titolo = #"Warning";
NSString *messaggio = #"There are empty fileds!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
} else {
NSString *imageName = self.nomeGiocata.text;
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
UIImage * imageToSave = self.imageViewPick.image;
NSData * binaryImageData = UIImageJPEGRepresentation(imageToSave, 1.0);
[binaryImageData writeToFile:[basePath stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.jpg", imageName]] atomically:YES];
NSManagedObjectContext *context = [self managedObjectContext];
[self.managedObjectContext setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];
newScheda = [NSEntityDescription
insertNewObjectForEntityForName:#"Archive"
inManagedObjectContext:context];
newScheda.immagine = [NSString stringWithFormat:#"%#.jpg", imageName];
newScheda.nome = nomeGiocata.text;
int bet = [importoGiocato.text intValue];
newScheda.giocata = [NSNumber numberWithInt:giocata];
addSched = balance[currentRecord];
int insert = [addSched.totScommesso intValue];
addSched.totScommesso = [NSNumber numberWithInt:insert + bet];
int aggiungiSched = [addSched.totSchedGiocate intValue];
addSched.totSchedGiocate = [NSNumber numberWithInt:aggiungiSched + 1];
int balance = [addSched.totBilancio intValue];
addSched.totBilancio = [NSNumber numberWithInt:balance + giocata];
NSError *error;
if (![context save:&error]) {
NSLog(#"Error during the process: %#", [error localizedDescription]);
}
NSString *titolo = #“MyApp";
NSString *messaggio = #"Saved!";
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
[self clearFields];
}
How can empty a cache when i delete my Record? or have other idea?
Related
I am accessing contact from user phone. Everything is working perfectly but when I add it into the NSMutableArray then nothing is entered. In breakpoint when I click on array its showing 0X16bed870. My code is as follow.
-(void)mycontact
{
NSMutableArray * contactNumbersArray = [[NSMutableArray alloc] init];
CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
if (status == CNAuthorizationStatusDenied || status == CNAuthorizationStatusRestricted)
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:#"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:TRUE completion:nil];
return;
}
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *phone;
NSString *fullName;
NSString *firstName;
NSString *lastName;
UIImage *profileImage;
for (CNContact *contact in cnContacts) {
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
} else if (firstName == nil) {
fullName=[NSString stringWithFormat:#"%#",lastName];
} else {
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
UIImage *image = [UIImage imageWithData:contact.imageData];
if (image != nil) {
profileImage = image;
}else{
profileImage = [UIImage imageNamed:#"person-icon.png"];
}
for (CNLabeledValue *label in contact.phoneNumbers) {
phone = [label.value stringValue];
if ([phone length] > 0) {
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage,#"userImage",phone,#"PhoneNumbers", nil];
}
dispatch_async(dispatch_get_main_queue(), ^{
for(int j=0;j<[contactNumbersArray count];j++)
{
NSString *newString = [[contactNumbersArray[j] componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
contactNumbersArray[j]=newString;
}
});
}
}
}];
}
I am building a project where I am using ELCImagepickerController for multiple selection and then I am saving those selected image into core data. Now I am fetching those images in another VC and showing them into an UICollectionView.
But the problem I am facing here is the images are not properly showing in collectionView. I am having two confusions.
The images are properly saving into core data or not.
If the images are saved, then properly fetching or not.
Here I am entering selected images into core data
- (void)imagePicker:(SNImagePickerNC *)imagePicker didFinishPickingWithMediaInfo:(NSMutableArray *)info
{
_arrImages = [[NSMutableArray alloc]init];
_imgdata = [[NSMutableData alloc]init];
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = app.managedObjectContext;
Albums *objPhotos = (Albums *)[NSEntityDescription insertNewObjectForEntityForName:#"Albums" inManagedObjectContext:context];
//get images
for (int i = 0; i < info.count; i++) {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:info[i] resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
_imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[objPhotos setPhotosInAlbum:self.imageData];
} failureBlock:^(NSError *error) { }];
}
NSError * err = nil;
[context save:&err];
if (![context save:&err]) {
NSLog(#"Can't Save! %# %#", err, [err localizedDescription]);
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success!!" message:#"Photos Successfully Selected!" delegate:self cancelButtonTitle:#"DONE" otherButtonTitles:nil];
[alert show];
}
Here I am fetching those selected images
-(NSArray *)getMenCategoryList
{
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *moc=app.managedObjectContext;
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Albums" inManagedObjectContext:moc];
[fetch setEntity:entity];
NSError *error;
NSArray *result = [moc executeFetchRequest:fetch error:&error];
if (!result) {
return nil;
}
return result;
}
I am calling the fetching function in - (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section and returning the array count
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [[self getMenCategoryList] count];
}
And lastly, populating the images into collectionView here
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"albumCollectionViewCellCell" forIndexPath:indexPath];
Photos *objAlbumPhotos = (Photos *)[[self getMenCategoryList] objectAtIndex:indexPath.row];
UIImage *albumImg = [UIImage imageWithData:[objAlbumPhotos valueForKey:#"photosInAlbum"]];
UIImageView *photosimageview = (UIImageView *)[cell.contentView viewWithTag:1];
photosimageview.image = albumImg;
return cell;
}
Any help is highly appreciated.
NOTE: i am just edit your code Please confirm first as per your code and edit as per your requirement
step 1: generate Unique file name and save your image with that file name to your file path.
step 2: after successfully write your file then save that path to your core data.
step 3: for fetching use core data path to get images from directory.
- (NSString*)generateFileNameWithExtension:(NSString *)extensionString {
// Extenstion string is like #".png"
NSDate *time = [NSDate date];
NSDateFormatter* df = [NSDateFormatter new];
[df setDateFormat:#"dd-MM-yyyy-hh-mm-ss"];
NSString *timeString = [df stringFromDate:time];
int r = arc4random() % 100;
int d = arc4random() % 100;
NSString *fileName = [NSString stringWithFormat:#"File-%#%d%d%#", timeString, r , d , extensionString ];
NSLog(#"FILE NAME %#", fileName);
return fileName;
}
- (void)imagePicker:(SNImagePickerNC *)imagePicker didFinishPickingWithMediaInfo:(NSMutableArray *)info
{
_arrImages = [[NSMutableArray alloc]init];
_imgdata = [[NSMutableData alloc]init];
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = app.managedObjectContext;
Albums *objPhotos = (Albums *)[NSEntityDescription insertNewObjectForEntityForName:#"Albums" inManagedObjectContext:context];
//get images
for (int i = 0; i < info.count; i++) {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:info[i] resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
_imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSString *strfilename = [self generateFileNameWithExtension:#".jpg"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:strfilename];
[_imageData writeToFile:filePath atomically:YES];
[objPhotos setPhotosInAlbum:filePath];
} failureBlock:^(NSError *error) { }];
}
NSError * err = nil;
[context save:&err];
if (![context save:&err]) {
NSLog(#"Can't Save! %# %#", err, [err localizedDescription]);
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success!!" message:#"Photos Successfully Selected!" delegate:self cancelButtonTitle:#"DONE" otherButtonTitles:nil];
[alert show];
}
I use GoldRaccoon for ftp-upload in my iOS-Application. The filetransfer works perfekt with txt-files up to many mb size. But images and pdf-files would be corrupted when they be uploaded.
There is no error and the upload seems to be successfull.
When i look into the iPad in the folder of the application (with iExplorer), there the files are good. Its also equal how big the size of the image is. Also its equal if it is a jpg or a png.
Also the files all existing when I start the upload.
- (void)uploadFilesToFTP:(Objekt *)objekt withCsvFilePath:(NSString *)csvLocalFilePath {
__block typeof(self) bself = self;
[self.library enumerateGroupsWithTypes:ALAssetsGroupAlbum
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if ([[group valueForProperty:ALAssetsGroupPropertyName] isEqualToString:self.albumName]) {
InfoLogMy(#"found album %#", self.albumName);
self.groupToAddTo = group;
}
}
failureBlock:^(NSError* error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Fehler" message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[alertView show];
return;
}];
// dateien
InfoLogMy("Count of files %d", objekt.dateien.count);
for (Datei *datei in objekt.dateien)
{
InfoLogMy(#"Upload starts");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dateiPath = [documentsDirectory stringByAppendingPathComponent:datei.dateiname];
NSError *error;
NSData *data = [[NSData alloc] initWithContentsOfFile:dateiPath options:NSDataReadingUncached error:&error];
if( [[NSFileManager defaultManager] fileExistsAtPath:dateiPath] )
{
if (!error) {
if (datei.zimmer != nil) {
// original image
UIImage *originalImage = [UIImage imageWithData:data];
__block typeof(self) bself = self;
//Bild wird in das Photoalbum des iPads als Sicherung abgelegt.
//Dies ist nicht mit PDF-Dokumenten möglich
[self.library writeImageToSavedPhotosAlbum:[originalImage CGImage]
metadata:nil
completionBlock:^(NSURL* assetURL, NSError* error) {
if (error.code == 0) {
// try to get the asset
[self.library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
// assign the photo to the album
[bself.groupToAddTo addAsset:asset];
}
failureBlock:^(NSError* error) {
InfoLogMy("failed to retrieve image asset:\nError: %# ", [error localizedDescription]);
}];
}
else {
InfoLogMy("saved image failed.\nerror code %i\n%#", error.code, [error localizedDescription]);
}
}];
}
// copy of image
NSString *filenameCopy = [NSString stringWithFormat:#"copy-%#", datei.dateiname];
NSString *localFilePathCopy = [documentsDirectory stringByAppendingPathComponent:filenameCopy];
BOOL copyFileExists = [[NSFileManager defaultManager] fileExistsAtPath:localFilePathCopy];
BOOL hasPaths = ([[datei.zeichnungen allObjects] count] > 0);
BOOL hasSymbols = ([[datei.symbole allObjects] count] > 0);
NSString *fileExtension = [datei.dateiname substringWithRange:NSMakeRange(datei.dateiname.length - 3, 3)];
BOOL isPDF = ([fileExtension isEqualToString:#"pdf"]);
if (copyFileExists == YES && (hasPaths == YES || hasSymbols == YES|| isPDF == YES)) {
NSError *error;
NSData *dataCopy = [[NSData alloc] initWithContentsOfFile:localFilePathCopy options:NSDataReadingUncached error:&error];
if (isPDF == NO) {
UIImage *copyImage = [UIImage imageWithData:dataCopy];
[self.library writeImageToSavedPhotosAlbum:[copyImage CGImage]
metadata:nil
completionBlock:^(NSURL* assetURL, NSError* error) {
if (error.code == 0) {
InfoLogMy(#"saved image completed:\nurl: %#", assetURL);
// try to get the asset
[self.library assetForURL:assetURL
resultBlock:^(ALAsset *asset) {
// assign the photo to the album
[bself.groupToAddTo addAsset:asset];
}
failureBlock:^(NSError* error) {
InfoLogMy(#"failed to retrieve image asset:\nError: %# ", [error localizedDescription]);
}];
}
else {
InfoLogMy(#"saved image failed.\nerror code %i\n%#", error.code, [error localizedDescription]);
}
}];
}
if (!error) {
[self.requestsManager addRequestForUploadFileAtLocalPath:localFilePathCopy toRemotePath:[NSString stringWithFormat:#"%#%#", kFtpPathOutbox, filenameCopy]];
}
}
else
{
//Wenn die Datei keine Zuordnung zu einem Zimmer hat.
if (datei.zimmer != nil)
{
[self.requestsManager addRequestForUploadFileAtLocalPath:dateiPath toRemotePath:[NSString stringWithFormat:#"%#%#", kFtpPathOutbox, datei.dateiname]];
}
}
} else {
// TO DO: Alert mit Fehler
return;
}
}
else
{
InfoLogMy(#"Datei existiert leider nicht");
[Mbs writeLog:[NSString stringWithFormat:#"Datei existiert nicht (%#)", datei.dateiname]];
}
}
NSArray *parts = [csvLocalFilePath componentsSeparatedByString:#"/"];
NSString *remotePath = [NSString stringWithFormat:#"%#%#", kFtpPathOutbox, [parts lastObject]];
[self.requestsManager addRequestForUploadFileAtLocalPath:csvLocalFilePath toRemotePath:remotePath];
self.requestsManagerFailed = NO;
[self.requestsManager startProcessingRequests];
}
i'm new to blocks, I have a class of requests with static methods to call me back on UIViewControllers with some blocks
this is the method implementation :
(putting a breakpoint on the block(something) DOES stop there, like it should)
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*callBackArray))block
{
if ([text isEqualToString:#""] || [text isEqualToString:#" "])
{
block(nil);
return;
}
NSString * key = #"someActualKeyHere";
;
NSString * finalText;
NSArray *tagschemes = [NSArray arrayWithObjects:NSLinguisticTagSchemeLanguage, nil];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options:0];
[tagger setString:text];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
if ([language isEqualToString:#"he"])
{
finalText = [text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
else
{
finalText = [text stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
}
NSString *urlString = [NSString stringWithFormat:
#"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%#&types=geocode&sensor=true&key=%#",finalText,key];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 2
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (!responseObject && ![responseObject respondsToSelector:#selector(dataWithData:)])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving "
message:#"ERROR"
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
return ;
}
NSData * responseData = [NSData dataWithData:responseObject];
NSString *responseString = [NSString stringWithUTF8String:[responseData bytes]];
NSError *err;
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error Retrieving Weather"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
this is how I call it, notice the NSLog, i put a breakpoint on it and its never called
which is exactly what I want to occur.
[Requests requestSuggestedLocationsForText:text withBlock:^(NSArray *callBackArray)
{
NSLog(#"ROFL");
}];
for the record, I have tried the same method with a different signature (without the returning variable name like so :
+(void)requestSuggestedLocationsForText:(NSString*)text withBlock:(void (^)(NSArray*))block;
still didn't fire my breakpoint :(
I think that this:
if ([responseString respondsToSelector:#selector(JSONObjectWithData:options:error:)])
{
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[responseString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&err];
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
Never runs because as far as I know, NSString doesn't declare JSONObjectWithData. Your break point will never hit because it will never be called.
It seems like it could just be:
NSData * responseData = [NSData dataWithData:responseObject];
NSError *err;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
if (!err) {
NSArray * predictions = [json valueForKey:#"predictions"];
block(predictions);
}
else {
block(nil);
}
The other way you convert it to a string, then back to data, why not just keep it as data?
Hi I have tried some code for new user registration using XMPPFrameWork in IOS.
-(IBAction)Registaton:(id)sender
{
// iPhoneXMPPAppDelegate *appDelegate =(iPhoneXMPPAppDelegate *)[[UIApplication sharedApplication]delegate];
[[[self appDelegate] xmppStream] connectWithTimeout:XMPPStreamTimeoutNone error:nil];
NSString *username = self.username.text;
NSString *password = self.password.text;
NSString *name =self.name.text;
NSString *email=self.email.text;
NSMutableArray *elements = [NSMutableArray array];
[elements addObject:[NSXMLElement elementWithName:#"username" stringValue:username]];
[elements addObject:[NSXMLElement elementWithName:#"password" stringValue:password]];
[elements addObject:[NSXMLElement elementWithName:#"name" stringValue:name]];
[elements addObject:[NSXMLElement elementWithName:#"email" stringValue:email]];
[[[self appDelegate] xmppStream] registerWithElements:elements error:nil];
NSLog(#"Register ====%#",[[self appDelegate] xmppStream]);
//[[[self appDelegate] xmppStream] registerWithPassword:elements error:nil];
}
but through this method i am not able register on server. it gives me connecting to Xmppstream Please wait.. Can anyone help me how can i create a new account on server using XMPPFrameWork in ios.
Try this. Its works fine for me
- (void)updateAccountInfo
{
//NSString *domain = [[NSString alloc] initWithString:#"192.168.1.100"];
//int port = 5222;
NSString *usname =[[NSString alloc] initWithString:self.txtUsername.text];
NSString *juser =[[NSString alloc] initWithString:[usname stringByAppendingString:#"your server ip"]];
XMPPJID *jid = [XMPPJID jidWithString:juser];
[self xmppStream].myJID =jid;
allowSelfSignedCertificates = NSOnState;
allowSSLHostNameMismatch = NSOnState;
NSUserDefaults *dflts = [NSUserDefaults standardUserDefaults];
//[dflts setObject:domain forKey:#"Account.Server"];
// [dflts setObject:(port ? [NSNumber numberWithInt:port] : nil)
// forKey:#"Account.Port"];
[dflts setObject:juser
forKey:#"Account.JID"];
[dflts setObject:#"ios"
forKey:#"Account.Resource"];
[dflts setBool:useSSL forKey:#"Account.UseSSL"];
[dflts setBool:allowSelfSignedCertificates forKey:#"Account.AllowSelfSignedCert"];
[dflts setBool:allowSSLHostNameMismatch forKey:#"Account.AllowSSLHostNameMismatch"];
[dflts setBool:YES forKey:#"Account.RememberPassword"];
[dflts setObject:self.txtPasswd.text forKey:#"Account.Password"];
[dflts synchronize];
}
- (void)createAccount
{
[self updateAccountInfo];
NSError *error = nil;
BOOL success;
if(![[[self appDelegate] xmppStream] isConnected])
{
if (useSSL)
success = [[self xmppStream] oldSchoolSecureConnectWithTimeout:XMPPStreamTimeoutNone error:&error];
else
success = [[self xmppStream] connectWithTimeout:XMPPStreamTimeoutNone error:&error];
}
else
{
//NSString *password = [[NSString alloc] initWithString:#"321" ];
success = [[self xmppStream] registerWithPassword:self.txtPasswd.text error:&error];
}
if (success)
{
[self appDelegate].isRegistering = YES;
}
else
{
NSLog(#"not succeed ");
}
}
- (void)xmppStreamDidRegister:(XMPPStream *)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Registration" message:#"Registration with XMPP Successful!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error{
DDXMLElement *errorXML = [error elementForName:#"error"];
NSString *errorCode = [[errorXML attributeForName:#"code"] stringValue];
NSString *regError = [NSString stringWithFormat:#"ERROR :- %#",error.description];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Registration with XMPP Failed!" message:regError delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
if([errorCode isEqualToString:#"409"]){
[alert setMessage:#"Username Already Exists!"];
}
[alert show];
}
A simple and WORKING approach which HAS WORKED for me
NSString *username = #"rohit#XMPP_SERVER_IP_HERE"; // OR [NSString stringWithFormat:#"%##%#",username,XMPP_BASE_URL]]
NSString *password = #"SOME_PASSWORD";
AppDelegate *del = (AppDelegate *)[[UIApplication sharedApplication] delegate];
del.xmppStream.myJID = [XMPPJID jidWithString:username];
NSLog(#"Does supports registration %ub ", );
NSLog(#"Attempting registration for username %#",del.xmppStream.myJID.bare);
if (del.xmppStream.supportsInBandRegistration) {
NSError *error = nil;
if (![del.xmppStream registerWithPassword:password error:&error])
{
NSLog(#"Oops, I forgot something: %#", error);
}else{
NSLog(#"No Error");
}
}
// You will get delegate called after registrations in either success or failure case. These delegates are in XMPPStream class
// - (void)xmppStreamDidRegister:(XMPPStream *)sender
//- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error