我有一个 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/