6

in my ios (swift) app, I have created main.swift in which I am setting a global variable against checking an NSDefault to check for ads removed.

then in each viewcontroller, i am first checking against that global variable and removing ads if appropriate before showing the view.

problem is that xcode does not like @UIApplicationMain in AppDelegate.swift because i have a main.swift. If I remove the line @UIApplicationMain the app crashes on launch.

Am I implementing main.swift wrong?

TPCO
  • 301
  • 1
  • 4
  • 9

4 Answers4

10

Your main.swift file will need to look something like this:

import Foundation
import UIKit

// Your initialization code here

UIApplicationMain(C_ARGC, C_ARGV, nil, NSStringFromClass(AppDelegate))

UIApplicationMain will start the event loop and prevent the app from exiting.

C_ARGC and C_ARGV are Swift vars that represent the C parameters that are passed in through main, namely int argc and char *argv[].

UPDATE 2016-01-02: C_ARGC and C_ARGV have been replaced by Process.argc and Process.unsafeArgv respectively. [source]

Community
  • 1
  • 1
Ryan H.
  • 7,374
  • 4
  • 39
  • 46
7

as of the very good answer to the question How do I access program arguments in Swift? from Darrarski...

The Swift 3 syntax would be:

//
//  main.swift
//

import Foundation
import UIKit

// very first statement after load.. the current time
let WaysStartTime = CFAbsoluteTimeGetCurrent()

// build the parameters for the call to UIApplicationMain()
let argc = CommandLine.argc
let argv = UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(to: UnsafeMutablePointer<Int8>.self, capacity: Int(CommandLine.argc))

// start the main loop
UIApplicationMain(argc, argv, nil, NSStringFromClass(AppDelegate.self))

and don't forget to remove the "@UIApplicationMain" from AppDelegate.swift as it would be redundant and causing a compiler error.

Hardy_Germany
  • 1,259
  • 13
  • 19
5

Thats how the main.swift should look in Swift 5

Hardy_Germany's answer gives warning in Xcode 10.2.

//
//  main.swift
//  TopLevelCode
//
//  Created by Stoyan Stoyanov on 04/04/2019.
//  Copyright © 2019 Stoyan Stoyanov. All rights reserved.
//

import UIKit
import Foundation

UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))

also again don't forget to remove the @UIApplicationMain tag from your AppDelegate read more about it here

Stoyan
  • 1,265
  • 11
  • 20
3

Swift 1.2 format:

UIApplicationMain(Process.argc, Process.unsafeArgv, nil, NSStringFromClass(AppDelegate))

superarts.org
  • 7,009
  • 1
  • 58
  • 44