du6333137 2015-12-23 09:15
浏览 40
已采纳

Swift 2 - 使用PHP在数据库中插入设备令牌

EDIT: I'm developing an iOS application, which uses a webview, that has push notification and I'm trying to pass the device token to a php file (sampleIndex.php) for database registration.

My attempt on posting the device token isn't working. Here's the code:

EDIT (2): My current code is based from @mat 's answer (same concept, but cleaner)

extension NSData {
func hexString() -> String {
    // "Array" of all bytes:
    let bytes = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count:self.length)
    // Array of hex strings, one for each byte:
    let hexBytes = bytes.map { String(format: "%02hhx", $0) }
    // Concatenate all hex strings:
    return (hexBytes).joinWithSeparator("")
  }

}


func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {

    let session = NSURLSession.sharedSession()
    let tk = deviceToken.hexString()
    let postBody = NSString(format: "token=%@", tk)
    let endBody = NSURL(string: "http://samplesite.com/subfolder/subfolder2/sampleIndex.php")
    let request = NSMutableURLRequest(URL: endBody!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 30.0)
    request.HTTPMethod = "POST";
    request.HTTPBody = postBody.dataUsingEncoding(NSUTF8StringEncoding)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    let dataTask = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in

        if data != nil {

            print("data: \(response)")

        } else {

            print("failed: \(error!.localizedDescription)")

        }

    }//closure

    dataTask.resume()
}

Why can't I get the value of tk? (token device). Am I missing something? Sorry, I'm just new to this.

EDIT (3) Here's the php code (sampleIndex.php) where the token is being requested:

<?php 
  include_once("includes/myConnect.php");
  $token = $_REQUEST['token'];

if (empty($token)) {
  $sql = "UPDATE sampleDB . sampleTB SET token= '0' WHERE id='8982'";
  $result = mysqli_query($conn, $sql);
}else{
  $sql = "UPDATE sampleDB . sampleTB SET token= '1' WHERE id='8982'";
  $result = mysqli_query($conn, $sql);
}

?>

(token sets to value " 0 " which proves that the device token fails to be passed on sampleIndex.php)

  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥25 需要一个能在H5中实现扫码的插件
      • ¥50 ArcGIS或MATLAB实现批量计算整个tif图像的EVI
      • ¥20 两个板子之间CAN通信ID号怎么设置
      • ¥15 两个板子CAN通信的话ID号怎么设置
      • ¥15 vue使用element-ui的el-upload上传图片至服务器,服务端使用的是node.js,图片上传成功,但界面显示不出来,是跨域问题?
      • ¥15 ANSYS APDL循环结果输出
      • ¥15 ArcGIS处理MODIS 09数据,计算EVI 像元值大小问题
      • ¥15 Python库一直装不好
      • ¥30 在linux上调用海康SDK没有进入函数内
      • ¥15 FreeRTOS有任务卡死