How do I make an HTTP request in Swift?

前端 未结 20 1520
不知归路
不知归路 2020-11-22 05:10

I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes

20条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 05:44

     var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10"
    
        NSLog("PostData: %@",post);
    
        var url1:NSURL = NSURL(string: url)!
    
        var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
    
        var postLength:NSString = String( postData.length )
    
        var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
    
        var reponseError: NSError?
        var response: NSURLResponse?
    
        var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
    
        if ( urlData != nil ) {
            let res = response as NSHTTPURLResponse!;
    
            NSLog("Response code: %ld", res.statusCode);
    
            if (res.statusCode >= 200 && res.statusCode < 300)
            {
                var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
    
                NSLog("Response ==> %@", responseData);
    
                var error: NSError?
    
                let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
    
                let success:NSInteger = jsonData.valueForKey("error") as NSInteger
    
                //[jsonData[@"success"] integerValue];
    
                NSLog("Success: %ld", success);
    
                if(success == 0)
                {
                    NSLog("Login SUCCESS");
    
                    self.dataArr = jsonData.valueForKey("data") as NSMutableArray
                    self.table.reloadData()
    
                } else {
    
                    NSLog("Login failed1");
                    ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
                }
    
            } else {
    
                NSLog("Login failed2");
                ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
    
            }
        } else {
    
            NSLog("Login failed3");
            ZAActivityBar.showErrorWithStatus("error", forAction: "Action2")
    }
    

    it will help you surely

提交回复
热议问题