Last active
February 3, 2019 12:48
-
-
Save shishirthedev/4a4aad090126beb30597629d1b7a898d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import UserNotifications | |
import Firebase | |
import FirebaseInstanceID | |
import FirebaseMessaging | |
@UIApplicationMain | |
class AppDelegate: UIResponder, UIApplicationDelegate { | |
var window: UIWindow? | |
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { | |
// Override point for customization after application launch. | |
FirebaseApp.configure() | |
registeerForPushNotifications() | |
return true | |
} | |
func applicationWillResignActive(_ application: UIApplication) { | |
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. | |
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. | |
} | |
func applicationDidEnterBackground(_ application: UIApplication) { | |
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. | |
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. | |
} | |
func applicationWillEnterForeground(_ application: UIApplication) { | |
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. | |
} | |
func applicationDidBecomeActive(_ application: UIApplication) { | |
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. | |
} | |
func applicationWillTerminate(_ application: UIApplication) { | |
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. | |
} | |
} | |
extension AppDelegate: MessagingDelegate { | |
// Called when FCM token is received | |
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { | |
print("FCM TOKEN: \(fcmToken)") | |
} | |
// Called when FCM token is refreshed | |
func messaging(_ messaging: Messaging, didRefreshRegistrationToken fcmToken: String) { | |
print("FCM TOKEN UPDATED \(fcmToken)") | |
} | |
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) { | |
print("RECEIVE REMOTE MESSAGE") | |
} | |
} | |
extension AppDelegate: UNUserNotificationCenterDelegate { | |
// Need To register for Notification first. First need to get access for local notification and then register for remote notifications. | |
public func registeerForPushNotifications(){ | |
if #available(iOS 10.0, *){ | |
print("IOS => 10") | |
let currentNotificationCenter = UNUserNotificationCenter.current() | |
currentNotificationCenter.getNotificationSettings { (settings) in | |
if settings.authorizationStatus == .authorized{ | |
print("AUTHORIZED") | |
DispatchQueue.main.async { | |
if !UIApplication.shared.isRegisteredForRemoteNotifications{ | |
print("NOT REGISTERED FOR PUSH NOTIFICATION") | |
currentNotificationCenter.delegate = self | |
UIApplication.shared.registerForRemoteNotifications() | |
Messaging.messaging().delegate = self | |
}else{ | |
print("REGISTERED FOR PUSH NOTIFICATION") | |
} | |
} | |
}else if settings.authorizationStatus == .notDetermined{ | |
print("NOT DETERMINED") | |
currentNotificationCenter.requestAuthorization(options: [.alert, .badge, .sound], completionHandler: { (granted, error) in | |
if error == nil && granted{ | |
DispatchQueue.main.async { | |
currentNotificationCenter.delegate = self | |
UIApplication.shared.registerForRemoteNotifications() | |
Messaging.messaging().delegate = self | |
} | |
}else{ | |
self.showAlertToEnableFromSettings() | |
} | |
}) | |
}else if settings.authorizationStatus == .denied{ | |
print("DENIED") | |
self.showAlertToEnableFromSettings() | |
} | |
} | |
}else{ | |
DispatchQueue.main.async { | |
if !UIApplication.shared.isRegisteredForRemoteNotifications{ | |
let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound] | |
let setting = UIUserNotificationSettings(types: type, categories: nil) | |
UIApplication.shared.registerUserNotificationSettings(setting) | |
UIApplication.shared.registerForRemoteNotifications() | |
Messaging.messaging().delegate = self | |
} | |
} | |
} | |
} | |
// Called If Failed to register for remote message (push notifications) | |
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { | |
print(" DID FAILED TO REGISTER FOR PUSH NOTIFICATION") | |
} | |
// Called if success to register for remote message (push notifications) | |
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { | |
Messaging.messaging().apnsToken = deviceToken | |
print("REGISTERED FOR PUSH NOTIFICATION") | |
} | |
// Called When Cloud message arrived and App in foreground.... | |
@available(iOS 10.0, *) | |
func userNotificationCenter(_ center: UNUserNotificationCenter, | |
willPresent notification: UNNotification, | |
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { | |
print(" APP IN FOREGROUND") | |
completionHandler([.alert, .badge, .sound]) | |
} | |
// Called When Cloud Message arrived and App in background or closed | |
@available(iOS 10.0, *) | |
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { | |
print("APP IN BACKGROUND") | |
} | |
// Called When Silent Push Notification arrived | |
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { | |
print(" SILENT PUSH NOTIFICATION") | |
} | |
func showAlertToEnableFromSettings() { | |
let alert = UIAlertController(title: "WARNING", message: "Please enable access to Notifications in the Settings app.", preferredStyle: .alert) | |
let settingsAction = UIAlertAction(title: "OPEN SETTINGS", style: .default) { (alertAction) in | |
guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return } | |
if UIApplication.shared.canOpenURL(settingsUrl){ | |
if #available(iOS 10.0, *) { | |
UIApplication.shared.open(settingsUrl) | |
} else { | |
UIApplication.shared.openURL(settingsUrl) | |
// Fallback on earlier versions | |
} | |
} | |
} | |
let cancelAction = UIAlertAction(title: "CANCEL", style: .default, handler: nil) | |
alert.addAction(settingsAction) | |
alert.addAction(cancelAction) | |
DispatchQueue.main.async { | |
self.window?.rootViewController?.present(alert, animated: true, completion: nil) | |
} | |
} | |
} | |
import UIKit | |
class NetwrokController: NSObject { | |
func uploadImage(endUrl:String, | |
params: NSMutableDictionary){ | |
guard let request = createRequest(endUrl: endUrl, param: params) else { return } | |
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in | |
if error != nil { | |
print("error=\(String(describing: error))") | |
return | |
} | |
// You can print out response object | |
print("******* response = \(String(describing: response))") | |
// Print out reponse body | |
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) | |
print("****** response data = \(responseString!)") | |
} | |
task.resume() | |
} | |
// | |
// | |
// | |
// func createBody(parameters: [String: String]?, | |
// boundary: String, | |
// data: Data, | |
// mimeType: String, | |
// filename: String) -> Data { | |
// | |
// let body = NSMutableData() | |
// let boundaryPrefix = "--\(boundary)\r\n" | |
// | |
// if let params = parameters{ | |
// if !params.isEmpty{ | |
// for (key, value) in params { | |
// body.appendString(boundaryPrefix) | |
// body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") | |
// body.appendString("\(value)\r\n") | |
// | |
// } | |
// } | |
// | |
// } | |
// | |
// body.appendString(boundaryPrefix) | |
// body.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n") | |
// body.appendString("Content-Type: \(mimeType)\r\n\r\n") | |
// body.append(data) | |
// body.appendString("\r\n") | |
// body.appendString("--".appending(boundary.appending("--"))) | |
// return body as Data | |
// } | |
// Creating Request for multi part | |
func createRequest (endUrl : String, | |
param : NSMutableDictionary) -> URLRequest? { | |
guard let urlToRequest = URL(string: endUrl) else { return nil} | |
var request: URLRequest = URLRequest(url: urlToRequest) | |
request.httpMethod = "POST" | |
let boundary = "Boundary-\(UUID().uuidString)" | |
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") | |
request.httpBody = createBodyForMultipleImage(parameters: param, boundary: boundary, mimeType: "image/jpg") | |
return request | |
} | |
// Creating multipart body for multipart request | |
func createBodyForMultipleImage(parameters: NSMutableDictionary?, | |
boundary: String, | |
mimeType: String) -> Data { | |
let body = NSMutableData() | |
let boundaryPrefix = "--\(boundary)\r\n" | |
if let params = parameters{ | |
for (key, value) in params { | |
if(value is String || value is NSString){ | |
body.appendString(boundaryPrefix) | |
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") | |
body.appendString("\(value)\r\n") | |
} | |
else if(value is [UIImage]){ | |
var i: Int = 0; | |
for image in value as! [UIImage]{ | |
let filename = "\(key)\(i)" | |
if let data = UIImageJPEGRepresentation(image, 1){ | |
body.appendString(boundaryPrefix) | |
body.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"\(filename)\"\r\n") | |
body.appendString("Content-Type: \(mimeType)\r\n\r\n") | |
body.append(data) | |
body.appendString("\r\n") | |
body.appendString("--".appending(boundary.appending("--"))) | |
i = i + 1 | |
} | |
} | |
} | |
} | |
} | |
return body as Data | |
} | |
} | |
extension NSMutableData { | |
func appendString(_ string: String) { | |
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: false) | |
append(data!) | |
} | |
} | |
import UIKit | |
class ViewController: UIViewController { | |
@IBOutlet weak var imageView: UIImageView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
} | |
@IBAction func onBtnClicked(_ sender: UIButton){ | |
if sender.tag == 0 { | |
let myPickerController = UIImagePickerController() | |
myPickerController.delegate = self; | |
myPickerController.sourceType = .photoLibrary | |
self.present(myPickerController, animated: true, completion: nil) | |
}else if sender.tag == 1{ | |
// let imageData = UIImageJPEGRepresentation(imageView.image!, 1) | |
let params = NSMutableDictionary() | |
params.setValue([imageView.image, imageView.image], forKey: "file") | |
NetwrokController().uploadImage(endUrl: "http://192.168.1.19/test-folder/upload.php", params: params) | |
} | |
} | |
} | |
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{ | |
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { | |
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage | |
picker.dismiss(animated: true, completion: nil) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment