Func sessionGetData () {
//创建 URI 对象
let urlstring = "http: //www.tuling123.com/"
let url = uRL (string: urlstring)
//创建请求对象
let request = URLRequest (url: url!)
let session = URISession . shared
iet datarask = session.dataTask (with: request,
completionHandler: ( (data, response, error) -> Void in
if error != nilf{
print (error.debugDescription)
}else{
let str = String (data: data!, encoding:
String. Encoding.utf8)
print (str!)
}) as URLSessionTask
//使用 resume 方法启动任务
dataTask. resume ( )
}
func sessionDownloadImage () {
//下载地址
let url = URL (string: "http: / /hangge.com/blog/ images/logo.png")
//请求
let request = ULRequest (url: url!)
let session = URLSession.shared
//下载任务
let downloadTask = session. downloadTask (with: request,
completionHandler: {
(location : URL?, response : URLResponse?, error:ErrOr?)
-> Void in
//输出下载文件原来的存放目录
print ("location : 1 (string (describing : 1ocation))")
//1ocation 位置转换
let locationPath = location?.path
//获取当前时间
let now = NsDate ()
//当前时间的时问戳
let timeInterval: TimeInterval = now. timeIntervalSince1970
let timestamp = String (timeInterval)
//拷贝到用户目录
let documents: String = NSHomeDirectory () + "/Documents/\(timeStamp).png"
//创建文件管理器
let fileManager = FileManager. default
try! fileManager moveItem (atPath: locationPath!, toPath:documents)
print ("new location: 1 (documents)")
} )
//使用resume 方法启动任务
downloadTask.resume ()
}
<?php
/**php 接收流文件
* @paramStringsfile 接收后保存的文件名
* @return boolean
* /
function receiveStreamFile ($receiverile) {
$streampata = isset (SCLOBALST 'HTTP RAW POST_ DATA'])? SGLOBATS L'HTTP_RAW POST DATA'] : '';
if (empty ($streamData)) {
$streamData = file_get_contents ('php://input");
}
if ($streamData!='') {
$ret = file _put_contents ($receiveFile, $streamData, true);
}else {
$ret = false;
}
rqeeturn $ret;
}
// 定义服务器存储路径和文件名
$receiverile = $_SERVERL" DOCUMENI ROOT"J ."/ uploadFiles / swift . png";
echo $receiveFile;
$ret = receiveStreamFile ($receiveFile) ;
echo json_ encode (array ('success ' => (bool) sret))i
?>
func sessionUploadPhp () {
//上传地址
let uri = URL(string: "http://localhost/uploadSwift.php")
//1.创建会话对象
let session = URLSession.shared
//请求
var request - URLecuest (url: uri!, cachePolicy: •reloadIgnoringCacheData)
request.httpMethod = "POST"
//上传数据流
iet tileImage = Bundle. main.path (forResource : "beel ", ofType: "png")
iet ingData = try! Data (contentsOf: URL (til eURIWi thPath: tileImage !))
let uploadIask = session.uploadTask (with: request as URLRequest, from:imaData) {
(data: Data?, response: URLResponse?, error:Error?) -> Void in
//上传完毕后
if error != nill
print (error!)
}else {
let str = string (data: data!, encoding: string .Encoding .utf8)
print("上传完毕:\(String (describing:stz))")
}
}
//使用resume 方法启动任务
uploadTask.resume ()
}
import UIKit
import Foundation
let API Key = "EIpAlhdD715152EsiNgpUOF_"
let Secret Key = "P8EzWg4agjDOxABmKVBYSNyZ1YzGFqb_"
let token_ host = "https: //aip.baidubce.com/oauth/2.0/token?grant_type=client_ credentials&client id=\(API Key) &client secret =\ (Secret_Key)"
var access token = ""
var expires in: Int32 = 0
if let url = URL (string: token host) {
URLSession. shared. dataTask (with: url) (data, response, error) in
if error != nil {
print ("network error")
}
else {
if let json = try? JSONSerialization.jsonObject (with: data!,options: allowFragments) as?[String:Any] {
access token = json ["access token"] as! String
expires in = ison["expires_in"las! Int32
print ("--------accesstoken------")
printaccess token)
print ("--------expires_time------")
print (expires_in)
}
}
}.resume()
}
else {
print("url error")
}
//以文本或者二进制方式读入源程序文件的 Ioader
public struct Loader
static func readTxt (file url:URI) ->String? {
do {
let source = try String (contentsOf: ur1)
return source
}
catch {
return nil
}
}
static func readBin (file url:URL) 一> Data? {
do {
let data = try Data (contentsOf: url)
return data
}
catch {
return nil
}
}
}
//Resources 中的文件,并把路径转化为 URL
let path = Bundle. main.path (forResource: "grcar. jpg", ofType: nil)
let url = URL (fileURLWithPath: path!)
let data = Loader.readBin (file: url)
if(data == nil) {
print ("File failed to load")
}
let data base64 str = data? .base64EncodedString()
let data base64 = data?.base64EncodedData ( )
access token="24.2ec96a68£742842900£07869929413ae.2592000.1598921312.282335-21737249"
let carType host ="https://aip.baidubce.com/rest/2.0/image-classify/v1/car" + "?access_token=" + "\(access_token)"
if let url = URL(string: carType_host)
var request = URLRequest (url: ur1)
request. setValue ("application/×-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
request.httpMethod = "POST"
let cs = NSCharacterSet (charactersIn: "/=+%") inverted
let image_urlEncode = data base64 str!addingPercentEncoding (withAllowedCharacters: cs)
let postString = "image=\(image urlEncode!) &top num=5&baike_num-1"
request.httpBody = postString.data (using:utf8)
URLSession.shared.dataTask(with: request) { (data,response, error) in
if error != nil {
print ("error")
}
else {
let rs = String (data: data!, encoding: String. Encoding.utf8)
print(rs!)
}
}
.resume ()
}
{
“log id" : 4368540366187197442,
"location result:
{
"width":386.4585876464844,
"top": 81.3405532836914,
"height": 183.9795532226562,
"left": 58.03330230712891
},
"result":
[
{
"score":0.9767324924468994,
"year": "2014-2017",
"baike_info":
{
"baike url": i/item/8E5gA5%87%87%91%9EE5/475143",
"image arl":
"/pic/5882b2b7a0a20cf47a91d7777c094b36acaf9910",
"description":
"2014 款奇瑞巴5 是国内科技家桥的引领者,带领消费者悦享领先科技。"
},
"name":"奇瑞E5"
},
{
"score : 0.007103727199137211,
"name":"奇瑞旗云",
"year": "2010-2013"
},
{
"score":0.003686367534101009,
"name":"奇瑞艾瑞泽 7",
"year": "2016-2017"
},
{
"score": 0.001757977530360222,
"name":“ 奇瑞53”,
"year": "2015-2017"
},
{
"score": 0.001047104829922318,
"name ":“ 奇瑞A5",
"year": "2015"
}
],
"color result" " 黒色"
}