-
Notifications
You must be signed in to change notification settings - Fork 0
/
iOS Helper
346 lines (291 loc) · 14.7 KB
/
iOS Helper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
//Background Task manager
.h
@property (nonatomic) UIBackgroundTaskIdentifier bgTask;
.m
In n applicationDidEnterBackground
UIApplication *app = [UIApplication sharedApplication];
self.bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:self.bgTask];
}];
In applicationDidBecomeActive
// End Background Task
if (self.bgTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
}
//Privacy and Terms click
self.lblTermsAndPolicy.isUserInteractionEnabled = true
let tapgesture = UITapGestureRecognizer(target: self, action: #selector(tappedOnLabel(_ :)))
tapgesture.numberOfTapsRequired = 1
self.lblTermsAndPolicy.addGestureRecognizer(tapgesture)
@objc func tappedOnLabel(_ gesture: UITapGestureRecognizer) {
guard let text = self.lblTermsAndPolicy.text else { return }
let privacyPolicyRange = (text as NSString).range(of: "Privacy Policy.")
let termsAndConditionRange = (text as NSString).range(of: "Terms of Use")
if gesture.didTapAttributedTextInLabel(label: self.lblTermsAndPolicy, inRange: privacyPolicyRange) {
let vc = self.storyboard?.instantiateViewController(identifier: "PrivacyPolicyVC")as! PrivacyPolicyVC
self.navigationController?.pushViewController(vc, animated: true)
} else if gesture.didTapAttributedTextInLabel(label: self.lblTermsAndPolicy, inRange: termsAndConditionRange){
let vc = self.storyboard?.instantiateViewController(identifier: "TermsVC")as! TermsVC
self.navigationController?.pushViewController(vc, animated: true)
}
}
//iOS SWIFT 13 Change
//Changes in iOS 13
didRegisterForRemoteNotificationsWithDeviceToken [deviceToken description]
iOS 12
<dd6ea57a 19bf0a05 c51692b6 e116c512 25fa04ef 9f84081d 576cc42f 639b62c3>
iOS 13
{length = 32, bytes = 0x35b57c5f cf576f17 55d221d4 67892ec4 ... 065ecf46 e1181548 }
——————————————
//You may use this method to fetch the device token on iOS 13 onwards:
//Objective-C:
+ (NSString *)stringFromDeviceToken:(NSData *)deviceToken { NSUInteger length = deviceToken.length;
if (length == 0) {
return nil; }
const unsigned char *buffer = deviceToken.bytes;
NSMutableString *hexString = [NSMutableString stringWithCapacity:(length * 2)];
for (int i = 0; i < length; ++i) {
[hexString appendFormat:@"%02x", buffer[i]];
}
return [hexString copy]; }
//Swift 5.0 (Untested)
class func string(fromDeviceToken deviceToken: Data?) -> String? { let length = deviceToken?.count ?? 0
iOS HELP
if length == 0 { return nil
}
let buffer = UInt8(deviceToken?.bytes ?? 0)
var hexString = String(repeating: "\0", count: length * 2) for i in 0..<length {
hexString += String(format: "%02x", buffer[i]) }
return hexString }
—————————
//Common Bundle Id :
com.ebizz.temp
//Notification Center Inline :
NotificationCenter.default.post(name: Notification.Name("ChatScreen"), object: info, userInfo: nil)
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "ChatScreen"), object: nil, queue: nil) { (notification) in
let object = notification.object as? NSDictionary ?? nil UserDefaults.standard.set(object, forKey: "notification")
if(object != nil){
let userToChat : User = User()
userToChat.firebaseUID = object!["sender_id"] as? String ?? "" userToChat.strName = object!["username"] as? String ?? "" userToChat.strImageNAme = object!["image_url"] as? String ?? ""
let chatViewController = self.storyboard?.instantiateViewController(withIdentifier: "ChatViewController") as! ChatViewController
chatViewController.userToChat = userToChat
self.navigationController?.pushViewController(chatViewController, animated: true)
} }
//Background task Mgr :
var streamInBackground: UIBackgroundTaskIdentifier!
applicationDidEnterBackground {
self.beginBackgroundTask() }
applicationDidBecomeActive {
self.endBackgroundTask() }
extension AppDelegate {
func beginBackgroundTask() { self.streamInBackground =
UIApplication.shared.beginBackgroundTask(withName: "streamInBackground", expirationHandler: {
self.endBackgroundTask() })
}
func endBackgroundTask() {
if self.streamInBackground != UIBackgroundTaskIdentifier.invalid &&
(self.streamInBackground != nil) { UIApplication.shared.endBackgroundTask(self.streamInBackground) self.streamInBackground = UIBackgroundTaskIdentifier.invalid
} }
func setupNotification() {
let notificationCenter = UNUserNotificationCenter.current() notificationCenter.delegate = self
let options: UNAuthorizationOptions = [.alert, .sound, .badge] notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in if !didAllow {
print("User has declined notifications") }
} }
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent
notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert,.sound]) }
}
//P12 to Pem :
openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts
//Delete Archieve :
~/Library/Developer/Xcode/Archives
//OTP Textfield :
//Setup TextField
txtOTP1.addTarget(self, action: #selector(textFieldDidChange(textField:)),
for: .editingChanged)
txtOTP2.addTarget(self, action: #selector(textFieldDidChange(textField:)),
for: .editingChanged)
txtOTP3.addTarget(self, action: #selector(textFieldDidChange(textField:)),
for: .editingChanged)
txtOTP4.addTarget(self, action: #selector(textFieldDidChange(textField:)),
for: .editingChanged)
/**
this the text file change method
**/
@objc func textFieldDidChange(textField: UITextField){
let text = textField.text
if (text?.utf16.count)! >= 1 { switch textField {
case txtOTP1:
txtOTP2.becomeFirstResponder() case txtOTP2:
txtOTP3.becomeFirstResponder() case txtOTP3:
txtOTP4.becomeFirstResponder() case txtOTP4:
txtOTP4.resignFirstResponder() default:
break }
} else {
} }
//MARK:- UITextField Delegate
func textField(_ textField: UITextField, shouldChangeCharactersIn range:
NSRange, replacementString string: String) -> Bool { let maxLength = 1
let currentString: NSString = textField.text! as NSString let newString: NSString =
currentString.replacingCharacters(in: range, with: string) as NSString return newString.length <= maxLength
}
extension OTPViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.text = "" }
}
//Notification delay:
https://stackoverflow.com/questions/9204767/how-much-delay-of-ios-push-
notification#
https://docs.telerik.com/platform/backend-services/javascript/push-
notifications/troubleshooting/push-trb-ios.html
https://medium.com/yalantis-mobile/uber-underlying-technologies-and-how-
it-actually-works-526f55b37c6f
//HELP - HUBUC - User Defaults
//Replace data of For Loop in clearAll() in ALUserDefaultsHandler.m
NSMutableArray *arrMyData = [[NSMutableArray alloc] initWithObjects:@"isUserLogin",@"LoginData",@"ReturnedToken", @"OtherReturnedToken", @"UserRole", @"device_token", @"CurrentLatitude", @"CurrentLongitude", nil];
if (![arrMyData containsObject:defaultKeyString]) {
if([defaultKeyString hasPrefix:KEY_PREFIX] && ![defaultKeyString isEqualToString:APN_DEVICE_TOKEN]) {
[userDefaults removeObjectForKey:defaultKeyString];
[userDefaults synchronize]; }
}
//Cell Button click
# Swift :-
var btnOpenDateTap : (() -> Void)? = nil
@IBAction func stepBtnOpenDatePicker(_ sender: Any) { if let function = self.btnOpenDateTap{
function() }
}
Cell.btnOpenDateTap = {
}
# Obj C :-
@property (nonatomic, copy) void(^btnCloseTap)(void);
- (IBAction)btnCloseClick:(id)sender { self.btnCloseTap();
}
cell.btnCloseTap = ^{ };
//IMAGE PICKER Delegate :
UIImagePickerControllerDelegate, UINavigationControllerDelegate
//Initialisation :
//Image Picker
let imagePicker = UIImagePickerController() var imageData:String = ""
//btnClick :
imagePicker.delegate = self imagePicker.allowsEditing = true imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true, completion: nil)
//UITextView Placeholder
- (void)viewDidLoad {
commentTxtView.text = @"Comment"; commentTxtView.textColor = [UIColor lightGrayColor]; commentTxtView.delegate = self;
}
- (BOOL) textViewShouldBeginEditing:(UITextView *)textView {
commentTxtView.text = @""; commentTxtView.textColor = [UIColor blackColor]; return YES;
}
-(void) textViewDidChange:(UITextView *)textView {
if(commentTxtView.text.length == 0) { commentTxtView.textColor = [UIColor lightGrayColor]; commentTxtView.text = @"Comment"; [commentTxtView resignFirstResponder];
} }
-(void) textViewShouldEndEditing:(UITextView *)textView {
if(commentTxtView.text.length == 0) { commentTxtView.textColor = [UIColor lightGrayColor]; commentTxtView.text = @"Comment"; [commentTxtView resignFirstResponder];
} }
- (IBAction)addImage:(id)sender {
UIActionSheet *action = [[[UIActionSheet alloc] initWithTitle:@"Select image
from"
Photo Picker - iOS
delegate:self cancelButtonTitle:@"Cancel"
destructiveButtonTitle:nil otherButtonTitles:@"From library",@"From
camera", nil] autorelease];
[action showInView:self.view]; }
//#pragma mark - ActionSheet delegates
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex: (NSInteger)buttonIndex
{
if( buttonIndex == 0 ) {
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
UIImagePickerController *pickerView =[[UIImagePickerController alloc]init];
pickerView.allowsEditing = YES;
pickerView.delegate = self;
pickerView.sourceType = UIImagePickerControllerSourceTypeCamera; [self presentViewController:pickerView animated:YES completion:nil];
}
}else if( buttonIndex == 1 ) {
UIImagePickerController *pickerView = [[UIImagePickerController alloc] init];
pickerView.allowsEditing = YES; pickerView.delegate = self; [pickerView
setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[self presentViewController:pickerView animated:YES completion:nil];
} }
//#pragma mark - PickerDelegates
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
[self dismissViewControllerAnimated:YES completion:nil];
UIImage * img = [info valueForKey:UIImagePickerControllerEditedImage];
myImageView.image = img;
}
//Action sheet for iPad
alert.popoverPresentationController?.sourceView = sender alert.popoverPresentationController?.sourceRect = sender.bounds alert.popoverPresentationController?.permittedArrowDirections = .up
//Device support File
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/ DeviceSupport
//View Animation :
//MARK:- Pop in and out animation
func openDialog(hideView: UIView, animationView: UIView, type: String){
hideView.isHidden = false animationView.transform = .identity
animationView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {() -> Void in
animationView.transform = .identity
}, completion: {(finished: Bool) -> Void in
// do something once the animation finishes, put it here
}) }
func closeDialog(hideView: UIView, animationView: UIView, type: String){ UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut,
animations: {() -> Void in
animationView.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
}, completion: {(finished: Bool) -> Void in hideView.isHidden = true
if(type == "true"){
self.getExamList(start: self.strStartDateMain, end: self.strEndDateMain)
} })
}
//Facebook (PageId)
if ([[UIApplic,tion sh,redApplic,tion] c,nOpenURL:[NSURL URLWithString:@"fb://"]]) {
[[UIApplication sharedApplic,tion] openURL:[NSURL URLWithString:@"fb:// profile/100022140846004"]];
}
else {
[[UIApplic,tion sh,redApplic,tion] openURL:[NSURL URLWithString:@"https:// www.f,cebook.com/qer,,h.,pp.96"]];
}
//Twitter (usern1me)
if ([[UIApplic,tion sh,redApplic,tion] c,nOpenURL:[NSURL URLWithString:@"twitter://"]]) {
[[UIApplic,tion sh,redApplic,tion] openURL:[NSURL URLWithString:@"twitter:// user?screen_n,me=qer3,h"]];
}else{
[[UIApplic,tion sh,redApplic,tion] openURL:[NSURL URLWithString:@"https://twitter.com/qer3,h"]]; }
//Inst1gr1m (usern1me)
if ([[UIApplic,tion sh,redApplic,tion] c,nOpenURL:[NSURL URLWithString:@"inst,gr,m://"]]) {
// Redirection - Profile
[[UIApplic,tion sh,redApplic,tion] openURL:[NSURL URLWithString:@"inst,gr,m://user?usern,me=qer3,h"]];
}else{
[[UIApplic,tion sh,redApplic,tion] openURL:[NSURL URLWithString:@"https://www.inst,gr,m.com/qer3,h/"]];
}
//Send Firebase notification - Swift
func SendNotification() {
//Sending notification of assistance to selected user
let url = URL(string: "https://fcm.googleapis.com/fcm/send")!
let session = URLSession.shared
let userDeviceId = "YOUR_FCM_TOKEN"
let comment = Comment_Field.text!
let assistanceDepartmentName = DepartmentName_Field.text!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters = [
"to": userDeviceId,
"notification" :
[
"body": comment,
"title": "Assistance Required in " + assistanceDepartmentName + " Department.",
],
] as [String : Any]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("key="+YourFirebaseServerKey, forHTTPHeaderField: "Authorization")
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
print("Success Notification sent")
})
task.resume()
}