How can I call a text from a random switch case? - xcode

- (IBAction)postToTwitter:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:#"This is the text which should be called from switch case"];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}
////And here is my switch case just to give an idea to you
-(IBAction) random {
int text = arc4random() % 3;
switch (text) {
case 0:
textview.text = #"Text example 1";
break;
case 1:
textview.text = #"Text example 2";
break;
case 2:
textview.text = #"Text example 3";
break;
default:
break;
}
}
Just I want to input Text example 1, Text example 2 and Text example 3 to my Twit content while my switch case is changing.
Help please!!! :'(

Simply replace it with
[controller setInitialText:textview.text];

Related

IOS SWIFT PARSE : Pfcloud.callFunction

i have an old app in objective C using cloudcode to send pushes to back4app platform.
The app manage to send correctly the pushes and this is the code :
- (IBAction)inviaPush:(UIButton *)sender {
NSString *canale;
for (int i=0; i<=4; i++) {
switch (i) {
case 0:canale=#"TraduzioniEDI";
break;
case 1:canale=#"NavFtpYM";
break;
case 2:canale=#"InvioMailFTP";
break;
case 3:canale=#"VermasMto";
break;
case 4:canale=#"EdiAltova";
break;
default:
break;
}
NSString *testoPush =[NSString stringWithFormat:#"%# Test Invio %#", canale,[NSDate date]];
[PFCloud callFunctionInBackground:#"push"
withParameters:#{#"channels": #[canale], #"data": #{#"alert": testoPush,#"badge":#"Increment"}}
block:^( NSString *result, NSError *error) {
if (!error) {
NSLog(#"Risultato: %#",result);
} else{
NSLog(#"Errore %#",error);
}
}];
}
}
Running the code i receive the 5 pushes and in the info of back4app dashboard i find :
2020-03-02T01:14:53.533Z - Ran cloud function push for user undefined with:
Input: {"channels":["VermasMto"],"data":{"alert":"VermasMto Test Invio 2020-03-02 01:14:52 +0000"}}
Result: "Sent!!"
i tried to convert the program in swift
the code to send push is :
func inviaPush (){
var canale :String = ""
for i in 0...4
{
switch i {
case 0: canale = "TraduzioniEDI"
case 1: canale = "NavFtpYM"
case 2: canale = "InvioMailFTP"
case 3: canale = "VermasMto"
case 4: canale = "EdiAltova"
default: canale=""
}
let testoPush = "\(canale) Test invio - Swift"
PFCloud.callFunction(inBackground: "push", withParameters: ["channels": canale, "data": ["alert": testoPush,"badge":"Increment"]], block: {
(result: Any?, error: Error?) -> Void in
if error != nil {
if let descrip = error?.localizedDescription{
print(descrip)
}
}else{
print(result as! String)
}
})
}
}
in this case i receive no pushes, and in the info i find following :
2020-03-02T01:17:25.505Z - Ran cloud function push for user undefined with:
Input: {"channels":"NavFtpYM","data":{"alert":"NavFtpYM Test invio"}}
Result: "Sent!!"
2020-03-02T01:17:25.504Z - Can't count installations for PushStatus hm5hbCzDvd: bad $in value
Comparing the info shown in the dashboard i see a difference in input
in ojective C (Working) the in input the channel have a square bracket :
Input: {"channels":["VermasMto"],
while when sent from swift they have not
Input: {"channels":"NavFtpYM",
surely i'm calling the method PFCloud.callFunction in a wrong way.
Any suggestion ?
Fabrizio
the solution was simple ...
need to change
PFCloud.callFunction(inBackground: "push", withParameters: ["channels": canale, "data": ["alert": testoPush,"badge":"Increment"]], block: {
in
PFCloud.callFunction(inBackground: "push", withParameters: ["channels": [canale], "data": ["alert": testoPush,"badge":"Increment"]], block: {
Fabrizio

Xcode : Search Bar Filtering

Hy all, i have developed an application that searches a table view connected to a sqlite database.
A search Bar is added onto of the application and the search is working fine, but when i type, i need only the items STARTING by the letter typed appear.
This is my code till now :
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
for (Author* author in theauthors)
{ //[NSPredicate predicateWithFormat:#"SELECT * from books where title LIKE %#", searchBar.text];
NSRange nameRange = [author.name rangeOfString:text options:NSCaseInsensitiveSearch];
NSRange descriptionRange = [author.genre rangeOfString:text options:NSCaseInsensitiveSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredTableData addObject:author];
}
}
}
[self.tableView reloadData];
}
It was actually pretty simple. I just had to change the options file from options:NSCaseInsensitiveSearch to option:NSAnchoredSearch
It worked like a charm

How to check that current space is Dashboard?

Sample code is
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:#selector(activeSpaceDidChange:) name:NSWorkspaceActiveSpaceDidChangeNotification object:nil];
Then
- (void) activeSpaceDidChange:(NSNotification *)aNotification {
// code to check if current workspace is dashboard?
}
I want to check whether the current space is dashboard or not? Any idea?
The first think i have tried is get to the current space id according to this answer: Detecting when a space changes in Spaces in Mac OS X . The problem here is that the key kCGWindowWorkspace is deprecated in OSX 10.8. So there is no direct way to get this information.
In my solution now i check for different windows or owners which are only one the dashboard space or on all other spaces:
The user is on the dashboard if there is one window which kCGWindowName ends with .wdgt/
The user is not on the dashboard if there is one window with kCGWindowName == System Status Item Clone, kCGWindowOwnerName == SystemUIServer | Finder
So why i'm not just using the .wdgt/ check? -- Because if there is now widget on the dashboard this not working
So why i'm using more than one window check? -. Because i'm not jet sure which window is always on all spaces. At least System Status Item Clone and Finder are not always there.
Here my implementation is add this function as category to NSWorkspace
- (BOOL) userIsOnDashboardSpace {
NSArray* windowsInSpace = (__bridge NSArray *) CGWindowListCopyWindowInfo(kCGWindowListOptionAll | kCGWindowListOptionOnScreenOnly, kCGNullWindowID);
NSUInteger indexOfWidget = [windowsInSpace indexOfObjectPassingTest:^BOOL(NSDictionary* obj, NSUInteger idx, BOOL *stop) {
if ([obj objectForKey:(id)kCGWindowName]) {
NSString *name = (NSString *)[obj objectForKey:(id)kCGWindowName];
if ([name isEqualToString:#"System Status Item Clone"]) {
*stop = true;
return false;
}
if ([name hasSuffix:#".wdgt/"]) {
*stop = true;
return true;
}
}
if ([obj objectForKey:(id)kCGWindowOwnerName]) {
NSString *name = (NSString *)[obj objectForKey:(id)kCGWindowOwnerName];
if ([name isEqualToString:#"SystemUIServer"]) {
*stop = true;
return false;
}
if ([name isEqualToString:#"Finder"]) {
*stop = true;
return false;
}
}
return false;
}];
return indexOfWidget != NSNotFound;
}

How do i implement a message box in a Cocoa application?

I have implemented delete functionality in cocoa application now i want to show one message box when user click on delete button.
Take a look at NSAlert, which has a synchronous -runModal method:
NSAlert *alert = [[[NSAlert alloc] init] autorelease];
[alert setMessageText:#"Hi there."];
[alert runModal];
As Peter mentions, a better alternative is to use the alert as a modal sheet on the window, e.g.:
[alert beginSheetModalForWindow:window
modalDelegate:self
didEndSelector:#selector(alertDidEnd:returnCode:contextInfo:)
contextInfo:nil];
Buttons can be added via -addButtonWithTitle::
[a addButtonWithTitle:#"First"];
[a addButtonWithTitle:#"Second"];
The return code tells you which button was pressed:
- (void) alertDidEnd:(NSAlert *)a returnCode:(NSInteger)rc contextInfo:(void *)ci {
switch(rc) {
case NSAlertFirstButtonReturn:
// "First" pressed
break;
case NSAlertSecondButtonReturn:
// "Second" pressed
break;
// ...
}
}
Long time has passed since the accepted answer and things have changed:
Swift is becoming more and more popular.
beginSheetModalForWindow(_:modalDelegate:didEndSelector:contextInfo:) is deprecated, we should use beginSheetModalForWindow:completionHandler: instead.
Latest code sample in Swift:
func messageBox() {
let alert = NSAlert()
alert.messageText = "Do you want to save the changes you made in the document?"
alert.informativeText = "Your changes will be lost if you don't save them."
alert.addButtonWithTitle("Save")
alert.addButtonWithTitle("Cancel")
alert.addButtonWithTitle("Don't Save")
alert.beginSheetModalForWindow(window, completionHandler: savingHandler)
}
func savingHandler(response: NSModalResponse) {
switch(response) {
case NSAlertFirstButtonReturn:
println("Save")
case NSAlertSecondButtonReturn:
println("Cancel")
case NSAlertThirdButtonReturn:
println("Don't Save")
default:
break
}
}
In case you want a synchronous version:
func messageBox() {
let alert = NSAlert()
alert.messageText = "Do you want to save the changes you made in the document?"
alert.informativeText = "Your changes will be lost if you don't save them."
alert.addButtonWithTitle("Save")
alert.addButtonWithTitle("Cancel")
alert.addButtonWithTitle("Don't Save")
let result = alert.runModal()
switch(result) {
case NSAlertFirstButtonReturn:
println("Save")
case NSAlertSecondButtonReturn:
println("Cancel")
case NSAlertThirdButtonReturn:
println("Don't Save")
default:
break
}
}

Check if last characters of an NSString are numbers

Is it possible to see of a string ends with a number which length is not known?
"String 1" -> 1
"String 4356" -> 4356
"String" -> nil
If so, how can I determine that number?
To test that a string ends with numbers, you can use an NSPredicate, such as:
NSPredicate endsNumerically = [NSPredicate predicateWithFormat:#"SELF matches %#", #"\\d+$"];
[endsNumerically evaluateWithObject:string]; // returns TRUE if predicate succeeds
NSScanner is sometimes useful for extracting things from strings, but it doesn't scan backward. You could define a Gnirts (reverse string) class and use that with an NSScanner, but that's probably more hassle than it's worth.
NSString's rangeOfCharacterFromSet:options:, which I had hope to use, only looks for a single character (it's like strchr and strrchr, if you're familiar with C), but we can roll our own that returns a contiguous range of characters from a set (a little like strspn) as a category on NSString. While we're at it, let's include methods that return substrings rather than ranges.
RangeOfCharacters.h:
#interface NSString (RangeOfCharacters)
/* note "Characters" is plural in the methods. It has poor readability, hard to
* distinguish from the rangeOfCharacterFromSet: methods, but it's standard Apple
* convention.
*/
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet;
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask;
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask range:(NSRange)range;
// like the above, but return a string rather than a range
-(NSString*)substringFromSet:(NSCharacterSet*)aSet;
-(NSString*)substringFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask;
-(NSString*)substringFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask range:(NSRange)range;
#end
RangeOfCharacters.m:
#implementation NSString (RangeOfCharacters)
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet {
return [self rangeOfCharactersFromSet:aSet options:0];
}
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask {
NSRange range = {0,[self length]};
return [self rangeOfCharactersFromSet:aSet options:mask range:range];
}
-(NSRange)rangeOfCharactersFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask range:(NSRange)range {
NSInteger start, curr, end, step=1;
if (mask & NSBackwardsSearch) {
step = -1;
start = range.location + range.length - 1;
end = range.location-1;
} else {
start = range.location;
end = start + range.length;
}
if (!(mask & NSAnchoredSearch)) {
// find first character in set
for (;start != end; start += step) {
if ([aSet characterIsMember:[self characterAtIndex:start]]) {
#ifdef NOGOTO
break;
#else
// Yeah, a goto. If you don't like them, define NOGOTO.
// Method will work the same, it will just make unneeded
// test whether character at start is in aSet
goto FoundMember;
#endif
}
}
#ifndef NOGOTO
goto NoSuchMember;
#endif
}
if (![aSet characterIsMember:[self characterAtIndex:start]]) {
NoSuchMember:
// no characters found within given range
range.location = NSNotFound;
range.length = 0;
return range;
}
FoundMember:
for (curr = start; curr != end; curr += step) {
if (![aSet characterIsMember:[self characterAtIndex:curr]]) {
break;
}
}
if (curr < start) {
// search was backwards
range.location = curr+1;
range.length = start - curr;
} else {
range.location = start;
range.length = curr - start;
}
return range;
}
-(NSString*)substringFromSet:(NSCharacterSet*)aSet {
return [self substringFromSet:aSet options:0];
}
-(NSString*)substringFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask {
NSRange range = {0,[self length]};
return [self substringFromSet:aSet options:mask range:range];
}
-(NSString*)substringFromSet:(NSCharacterSet*)aSet options:(NSStringCompareOptions)mask range:(NSRange)range {
NSRange range = [self rangeOfCharactersFromSet:aSet options:mask range:range];
if (NSNotFound == range.location) {
return nil;
}
return [self substringWithRange:range];
}
#end
To use the new category to check that a string ends with digits or to extract the number:
NSString* number = [string substringFromSet:[NSCharacterSet decimalDigitCharacterSet]
options:NSBackwardsSearch|NSAnchoredSearch];
if (number != nil) {
return [number intValue];
} else {
// string doesn't end with a number.
}
Lastly, you can use a third party regular expression library, such as RegexKit or RegexkitLite.
I couldn't get the NSPredicate code above to work correctly, though it looks like it should. Instead I accomplished the same thing with
if ([string rangeOfString:#"\\d+$" options:NSRegularExpressionSearch].location != NSNotFound) {
// string ends with a number
}
Hat-tip to this answer.

Resources