I configured my app:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let pushSettings: UIUserNotificationSettings = UIUserNotificationSettings(
forTypes:[.Alert, .Badge, .Sound],
categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(pushSettings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
print("My token is: \(deviceToken)");
}
// Failed to register for Push
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Failed to get token; error: %#", error) //Log an error for debugging purposes, user doesn't need to know
}
Copy my device token, to my python script:
import time
from apns import APNs, Frame, Payload
apns = APNs(use_sandbox=True, cert_file='NodesDownCert.pem', key_file='NodesDownKey.pem')
# Send a notification
token_hex = 'xxx'
payload = Payload(alert="Hello World!", sound="default")
apns.gateway_server.send_notification(token_hex, payload)
I ran script, it didn't return errors, but i haven't received notifications at my Ipad. I tried php script from this tutorial, script returns "Message successfully delivered", but i'm still not receive any message. Php code here.
Any ideas how to debug or what is wrong ?
Related
I am getting this error when trying to connect to an API in flutter to get user data. The API is remote, the phone has connection to the internet, I'm using an android phone to build the APP.
this is the error.
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: SocketException: OS Error: Connection refused, errno = 111, address = address, port = 43798
for back end we are using PHP Laravel , but the API should be open to anyone who has the address at this point in development, so much so that the get request works both in Postman and in browser when calling.
As for the flutter function, this is the code being used.
Future<User> getUser(url) async {
print("here");
var params = {
"id": "01142",
};
Uri uri =
Uri.parse(url);
uri.replace(queryParameters: params);
final response = await http.get(
uri,
headers: <String, String>{
'Content-Type': 'application/json',
'Accept': "*/*",
'connection': 'keep-alive',
'Accept-Encoding': 'gzip, deflate, br',
'host': 'ipv4',
},
);
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
user = User.fromJson(jsonDecode(response.body));
print("NEW USER");
print(user);
return user;
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load user');
}
}
According to back end Laravel isnt using SSL either, what might be the problem?
I use FCM for notification.
In firebase console i can send notification, but by PHP code not received and cant custom it
PHP code :
$data['TITLE'] = $title;
$data['TEXT'] = $text;
$fcmFields = array('to'=>$to,
'data'=>$data,
'priority'=>'high',
'time_to_live'=>$time);
$headers = array('Authorization: key='.API_ACCESS_KEY,'Content-Type: application/json');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://fcm.googleapis.com/fcm/send');
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fcmFields));
$result = curl_exec($ch);
curl_close($ch);
return $result;
Note: by this php code i can send notification android devices
Swift Code :
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: authOptions, completionHandler: {_, _ in })
} else {
let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: #escaping (UIBackgroundFetchResult) -> Void) {
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
}
}
#available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: #escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: #escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
print(userInfo)
completionHandler()
}
}
extension AppDelegate : MessagingDelegate {
func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) {
print("Firebase registration token: \(fcmToken)")
let dataDict:[String: String] = ["token": fcmToken]
NotificationCenter.default.post(name: Notification.Name("FCMToken"), object: nil, userInfo: dataDict)
}
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
}
}
1- I can send notification by google console and received but not prints anything in my app log
2- I can send notification to android devices by php codes but i cant send for ios devices
3- didReceiveRemoteNotification completely not work
Can you help me ?
I add 'notification' in PHP code and fixed
$fcmFields = array('to'=>$to,
'data'=>$data,
'notification'=>array('title'=>'x','body'=>'y'),
'priority'=>'high',
'time_to_live'=>$time);
I tried to solved an issue regarding file upload with Alamofire (Link) (Swift 3.0) and retrieving them server-side using Slim PHP (Link) micro framework.
I'm trying to upload picture taken from the iPhone using
Alamofire.upload(multipartFormData:{
multipartFormData in
multipartFormData.append("value".data(/* ... */)!, withName :"key")
var idx = 1;
for imageRepresentation in imageData {
let pictureName = "pictures[]"
multipartFormData.append(imageRepresentation, withName: pictureName, mimeType: "image/jpeg")
idx += 1
}
},
to: uploadUrl,
method:.post,
headers: httpHeaders,
encodingCompletion: /* ... */
Here i'm almost sure that this script is working fine because when I hit https://httpbin.org/post I get back the encoded data base 64 image I've uploaded, so I'm quite sure that the issue comes from my server side code.
So, as I said, I'm using Slim PHP (Link) server side with this route
$this->post('/upload', function ($request, $response, $args) {
$request->getParsedBody(); //null
$request->getQueryParams(); // []
$request->getBody(); // {}
$request->getUploadedFiles(); // []
return /*Some JSON */
})->setName('upload');
Did I miss something ? Is there something I didn't understand ?
I already tried
Multipart/form-data example in slim micro framework
https://akrabat.com/psr-7-file-uploads-in-slim-3/
And the most weird thing is that the script works like a charm when executed from Paw API Explorer
Any help would be really appreciated ! Thanks.
For Uploading the image selected from photo library
In Swift 3 and Alamofire 4
Here is the Full Implementation of how to upload using Alamofire
Add the Following to your ViewController Class:
UIImagePickerControllerDelegate and UINavigationControllerDelegate
Create A Button:
First Create a button and implement the Following method in it for picker view
#IBAction func btnSelectProfileImageClicked(_ sender: Any) {
let ImagePicker = UIImagePickerController()
ImagePicker.delegate = self
ImagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(ImagePicker, animated: true, completion: nil)
}
Then Implement the following UIPicker Methods:
func imagePickerController( _ picker: UIImagePickerController,didFinishPickingMediaWithInfo info:[String : Any] )
{Imgprofile.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismiss(animated: true, completion: nil)}
Make Another Button Which Passes the data to URL using Alamofire and Give an #IBAction outlet to it to it :
Enter Following Data to it
#IBAction func btnUpdateProfileSelected(_ sender: Any) {
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(UIImageJPEGRepresentation(self.Imgprofile.image!, 1)!, withName: "Prescription", fileName: "Profile_Image.jpeg", mimeType: "image/jpeg")
}, to:" Your URL Here where You want to Upload")
{ (result) in
switch result {
case .success(let upload, _, _):
print(result)
upload.uploadProgress(closure: { (progress) in
print(progress)
})
upload.responseJSON { response in
//print response.result
print(response);
}
case .failure(let encodingError):
print(encodingError);
}
}
}
Thats all
Hope This helps
For Full sample code or any doubts please comment. I will provide you
the sample code for this. Which Includes the Fetching as well as
upload data using Alamofire.
Thanks
so I'm trying to create managed stripe accounts with PHP Swift and Alamofire. But it's not working at all.
Here's my PHP code:
<?php
require_once('vendor/autoload.php');
\Stripe\Stripe::setApiKey("My APIKEY");
$country = $_POST['country'];
$create = \Stripe\Account::create(array(
"country" => $country,
"managed" => true
)
);
?>
Here's my swift code:
#IBAction func createBtn(_ sender: Any) {
let card = STPCardParams()
card.number = "5200828282828210"
card.expMonth = 4
card.expYear = 2024
card.cvc = "242"
card.currency = "usd"
STPAPIClient.shared().createToken(withCard: card ,completion: {(token, error) -> Void in
if let error = error {
print("ERROR: \(error.localizedDescription)")
}
else if let token = token {
print(token)
self.createUsingToken(token:token)
}
})
}
func createUsingToken(token:STPToken) {
let requestString = "My request URL"
let params = ["token": token.tokenId, "country": "US"]
//This line of code will suffice, but we want a response
Alamofire.request(requestString, method: .post, parameters: params).responseJSON { (response) in
print("REQUEST: \(response.request!)") // original URL request
print("RESPONSE: \(response.response!)") // URL response
print("DATA: \(response.data!)") // server data
print("RESULT: \(response.result)") // result of response serialization
if let JSON = response.result.error {
print("JSON: \(JSON.localizedDescription)")
}
}
}
And I'm getting this error from Alamofire: JSON: Response could not be serialized, input data was nil or zero length.
Thanks for your help.
It looks like your Swift/Alamofire request is expecting a JSON response, but your PHP code is not sending any response at all: you're sending an account creation request to Stripe but then never outputting any data.
You likely want to prepare an array with the attributes that you expect in your Swift code, then output it as JSON at the end of your PHP script:
echo json_encode($result);
I am trying to connect to my localhost API (that I need to build along with the iOS swift app) that returns a json string. The API is written in Laravel 4 framework.
Here is the iOS Swift code to connect and receive the code:
func checkEmail() {
var request = NSMutableURLRequest(URL: NSURL(string: "http://localhost:3306/laravel/rojectapi/checkEmail"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["email":"myemail#me.com", "password":"password"] as Dictionary
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as NSDictionary
println("hey")
if(err) {
println(err!.localizedDescription)
}
else {
var success = json["success"] as? Int
println("Success: \(success)")
}
})
task.resume()
}
The Laravel PHP Route:
Route::post('/checkEmail', array(
'as' => 'checkEmail',
'uses' => 'FrontEndController#checkEmail'
));
And then the front-end-controller with the checkEmail method:
public function checkEmail() {
$validator = Validator::make(Input::all(), array(
'email' => 'required|unique:users|email'
));
if($validator->fails()) {
return $validator->messages()->toJson();
} else {
return Response::json(array('success' => true));
}
}
Am I not connecting to the server correctly? I need to do so on my iPhone 5s connected to my laptop, as well as in the emulator. I have tried name.local, localhost:<post> and name.local:<post> in the URL.
Update
I got the code from this tutorial
Either pass NSJSONReadingAllowFragments (.AllowFragments in Swift) or format your JSON properly.
A simple google search revealed that error 3840 is caused due to improperly formatted JSON being passed to the iOS JSON parser.
This occurs if the API is expecting some data from you and you are not able to send it or it is not being received by the APi, try to Echo out the parameter which are received by the API as a response to your iOS Request, It may also occur if you APi Implementation has some error in it, though you may be able to see this error in your Web Console.
I have this error, when i add languages to Localizations in project. When i add language, must change from "localizable strings" to "interface builder storyboard". I mean project of iOS app. Could help you.