#swift

Get Push Notification While App in Foreground iOS in Swift

by

If the application is running in the foreground, iOS won’t show a notification banner or alert. That is by design.

If we receive local or remote notifications while we app is running in the foreground, we’re responsible for passing the information to our users in an app-specific way. Where to handle and process such request?

userNotificationCenter(_:willPresent:withCompletionHandler:)

Asks the delegate how to handle a notification that arrived while the app was running in the foreground.

If your app is in the foreground when a notification arrives, the shared user notification center calls this method to deliver the notification directly to your app. If you implement this method, you can take whatever actions are necessary to process the notification and update your app. When you finish, call the completionHandler block and specify how you want the system to alert the user, if at all.

CONTINUE READING

Present Safari View Controller Modally instead of Push

by

When I launch safari view controller(SFSafariViewController) by way of present(_:animated:completion:) method, I do not get the default modal transition behaviour, instead the transition is that of push (sliding in from the right), as if I called pushViewController:animated:

SFSafariViewController

An object that provides a visible standard interface for browsing the web.
CONTINUE READING

How to Send Local Video to iMessage in Swift

by

This post assumes we have understanding about exporting to mp4 video. The use case example of the discussion exports a video and save it locally inside app’s folder: Document, Cache or Temporary. In my case I am doing some very basic composing of video and saving it to my temporary folder. I want to send this video or share it to my contacts through iMessage or MFMessageComposeViewController. Below is a brief idea on how I am exporting to mp4 video that saves in app’s temporary folder.


let exportURL = URL(fileURLWithPath: NSTemporaryDirectory())
          .appendingPathComponent("filename")
          .appendingPathExtension("mp4")
export.outputFileType = .mp4
export.outputURL = exportURL

export.exportAsynchronously {
  DispatchQueue.main.async {
    switch export.status {
    case .completed:
        print("success")
    default:
      print("Something went wrong during export.")
      print(export.error ?? "unknown error")
      break
    }
  }
}

Now, I found 2 easy effective ways to share or attach video to iMessage or MFMessageComposeViewController.

CONTINUE READING

How to get Deprecated keyWindow in Swift

by

Note: Discussion in this post assumes we are considering single window based scenario.

Sometimes I need to access the main window of my app to add some temporary views to it - making it appear forefront no matter at what depth of user’s navigation-flow I am in.

From old days of single window based app we have been using very convenient property handed to us: keyWindow

keyWindow
This property holds the UIWindow object in the windows array that is most recently sent the makeKeyAndVisible() message.


guard let window = UIApplication.shared.keyWindow else {return}

It has been long time. Now this has been deprecated from iOS 13 onwards.

We have our windows accessible from windows array:


let window = UIApplication.shared.windows[0]

A free assumption would be that first window in array would be the main window of the app - being the root. We want the root window so that any view being added be directly on top for our given purpose here. It worked good until unexpected happened. First object did not give UIWindow but UITextEffectsWindow. I could not add my view on the top anymore - adding to UITextEffectsWindow didn’t work for curiosity.

CONTINUE READING

How to Display Image in SKShapeNode

by

I have been using SKShapeNode extensively to draw quick graphics by filling them with CGPaths for quick visual debugging and making prototypes. For example I can create procedural mountains quickly with SKShapeNode. In early times of spritekit SKShapeNode didn’t have way to render images on it. We have fillTexture available now that allows texture to fill the shape.


let shapeNode = SKShapeNode()
shapeNode.fillTexture = SKTexture(imageNamed: “testImage")

But, Our SKShapeNode is displaying nothing.

Why is that?

CONTINUE READING

App crashing when saving photos from WKWebView

by

I stumbled upon a crash in my app. In my app I have a WKWebView that lets user access web. I tried saving image from a website by long pressing - general way we do in our iOS safari - and app crashed. This user experience behaviour of long pressing and saving image is very common.

The crash error is:

This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app’s Info.plist must contain an NSPhotoLibraryAddUsageDescription key with a string value explaining to the user how the app uses this data.

CONTINUE READING

UIImagepicker controller allowsEditing not working

by

Using native image picker system is easy and solves everyday basic needs of most apps.

UIImagePickerController
A view controller that manages the system interfaces for taking pictures, recording movies, and choosing items from the user’s media library.

Here is an example code that lets user pick images from photo library:


pickerController = UIImagePickerController()
pickerController?.delegate = self
pickerController?.mediaTypes = [“public.image”]
pickerController?.sourceType = .photoLibrary
self.present(pickerController!, animated: true, completion: nil)

We need to implement delegate methods that provides us media info from which we can extract image in our case if available. Here is a code


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    if let image = info[.originalImage] as? UIImage{
    }
}

info
A dictionary containing the original image and the edited image, if an image was picked; or a filesystem URL for the movie, if a movie was picked. The dictionary also contains any relevant editing information. The keys for this dictionary are listed in Editing Information Keys.

Our picked image resides inside the key .originalImage which is optional so if something went wrong then it will be nil.

Now, UIImagePickerController also supports basic crop. To activate crop we set the allowsEditing property to true. By default it is false.

CONTINUE READING

How to Get Substring With NSRange in Swift 5

by


Warning:

substring(with:)’ is deprecated: Please use String slicing subscript.

In Swift 5 we do no longer have access to substring() methods for they are deprecated. We will discuss all alternatives and understand them in details.

  • How to access Characters in String?
  • Why Int based Subscript is not available in Swift?
  • What is difference between Range and NSRange?
  • How does String Indices work?
  • How to create Range from String Indices?
  • How to get substring with Range?
  • How to get substring with NSRange?

CONTINUE READING

How to Fix Warning Attempt To Present UIAlertController in Swift

by

Warning: Attempt to present <UIAlertController: 0x7fa95080de00> on <MainViewController: 0x7fa94f8a5000> which is already presenting (null)

Warning of attempt to present view controller is common occurrence when making an easily made mistake. I will take Alert controller for an example to discuss.

Lets’s create a scenario to bring UIAlertController warning message and observe side effect to understand our situation more effectively. Then we will understand on how to fix warning attempt to present UIAlertController. I will present a Detail view controller modally from Main controller, and Main controller will be delegate object assigned to the property of Detail view controller. In our presented view controller I have a dismiss code when back button is pressed. Before dismissing the controller I will call the delegate object - Main controller in this case - to present Alert controller from Main controller.

CONTINUE READING

MFMessageComposeViewController shows blank white screen issue

by

We use an MFMessageComposeViewController object to display the standard message composition interface in order to send text messages in our app. Properties of MFMessageComposeViewController lets us populate pre-defined recipients and body message before presenting the interface.

Simple code to create and present MFMessageComposeViewController is:

            
if([MFMessageComposeViewController canSendText]){
    MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
    picker.messageComposeDelegate = self;
    picker.recipients =@[“1234”];
    picker.body = @“pre-defined message”;
    [self presentViewController:picker animated:YES completion:nil];
}
else{
    NSLog(@“Cannot send text”);
}
            
            
            
if MFMessageComposeViewController.canSendText() {
    let picker = MFMessageComposeViewController()
    picker.messageComposeDelegate = self;
    picker.recipients =[“1234”];
    picker.body = “pre-defined message”;
    self.present(picker, animated: true, completion: nil)
}
else{
    print(“Cannot send text”);
}
            
            

Not so distant, I had stumbled upon a very silly mistake that caused an MFMessageComposeViewController to show blank after presenting.

CONTINUE READING

Recommended posts