php - 使用 Swift 连接到 PHP 服务器

标签 php objective-c swift

我有一个 Objective C 连接到服务器的脚本:

NSURL *url = [NSURL URLWithString:@"http://localhost/project"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
  NSString *response = [request responseString];
  NSArray *results = [response componentsSeparatedByString:@", "]; 
  for (NSString* result in results) {
   NSString * trimmedResult = [result stringByTrimmingCharactersInSet:[NSCharacterSet   whitespaceAndNewlineCharacterSet]];
   if ([trimmedResult isEqualToString:@"failure"]) 
    NSLog(@"operation %i failed.", i + 1);
   }
 }

但现在我需要使用 Swift。在 Objective C 中连接并桥接到 swift 更容易,还是在 swift 中连接更容易?不过,我真的很想快速完成它。

最佳答案

我不熟悉您的第三方库,但您应该能够使用内置方法实现相同的目的,因为它似乎是一个简单的同步请求。试试这个:

let url = NSURL(string:"http://localhost/project")
let request = NSURLRequest(URL:url)
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)

let results = NSString(data:reply, encoding:NSUTF8StringEncoding)

// Continue your processing of results here...

更新 要使用 POST,请使用 NSMutableURLRequest。一般形式如下所示。很难找到的部分是NSURLProtocol.setProperty(...)。请参阅this page .

let url = NSURL(string:"http://localhost/project")
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url, cachePolicy: cachePolicy, timeoutInterval: 2.0)
request.HTTPMethod = "POST"

// set Content-Type in HTTP header
let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)

// set data
var dataString = "your data here" + boundaryConstant
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData

// set content length
NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)

var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)

let results = NSString(data:reply, encoding:NSUTF8StringEncoding)

关于php - 使用 Swift 连接到 PHP 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24508623/

相关文章:

php - 如何将 PHP 变量传递给 JavaScript 函数?

php - js上的数组数据——好用吗?

ios - 用内容填充 TableView

xcode - 为什么我到处都得到 "unexpected nil"?

PHP 向我上传的文件添加 2 个额外字节

php - 在 HTML 中以 SVG 格式显示图像

objective-c - 如何将图像设置为 UIImage

ios - 如何提高 OpenTok RTC(实时通信)中的视频质量/分辨率

iOS 6 - 在后台重新启动被杀死的应用程序

ios - 设置单元格高度取决于嵌入的collectionview的内容