标签: nsurlrequest

NSURLRequest缓存无法正常工作

我正在尝试缓存我的nsurlrequest数据.在此之前,我成功地从服务器下载数据,自从我尝试实现此缓存以来,它一直在使我的应用程序崩溃.我希望有人可以看看我到目前为止的代码,并帮助我让它工作..我想我已经完成了大约95%.

- (IBAction)setRequestString:(NSString *)string
{
    //Set database address
    NSMutableString *databaseURL = [[NSMutableString alloc] initWithString:@"http://127.0.0.1:29/"]; // imac development


    //PHP file name is being set from the parent view
    [databaseURL appendString:string];

    //call ASIHTTP delegates (Used to connect to database)
    NSURL *url = [NSURL URLWithString:databaseURL];

    //SynchronousRequest to grab the data, also setting up the cachePolicy
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0]; //if request dose not finish happen within 60 second timeout.

    //This nsdata will be used to put the cache into
    NSData …
Run Code Online (Sandbox Code Playgroud)

iphone nsurlconnection nsurlrequest ios

0
推荐指数
1
解决办法
3695
查看次数

使用NSURLRequest时出现错误的URL错误

我有下一个创建的NSURLRequest:

NSString *url=[NSString stringWithFormat:@"http://myserveradress.com/api/users/register?register_password=%@&register_password_confirm=%@&register_email=%@&register_terms=1&register_user=%@&process_registration=1&register_name=%@"
                   ,
                   [password stringByReplacingOccurrencesOfString:@" " withString:@"%"],[confirm stringByReplacingOccurrencesOfString:@" " withString:@"%"],[email stringByReplacingOccurrencesOfString:@" " withString:@"%"],[user stringByReplacingOccurrencesOfString:@" " withString:@"%"],[realName stringByReplacingOccurrencesOfString:@" " withString:@"%"]
                   ];
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    NSError *error;
    NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    NSString *result_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return result_string;
Run Code Online (Sandbox Code Playgroud)

结果字符串是http://myserveradress.ru/api/users/register?register_password=password&register_password_confirm=password&register_email=myname@mail.com&register_terms=1&register_user=myname&process_registration=1&register_name=Artem%Kulikov错误状态

Error Domain=NSURLErrorDomain Code=-1000 "bad URL" UserInfo=0x71e62b0 {NSUnderlyingError=0x71e6470 "bad URL", NSLocalizedDescription=bad URL}
Run Code Online (Sandbox Code Playgroud)

在浏览器中链接工作正常.问题只出在应用程序中.

url cocoa-touch objective-c nsurlrequest ios

0
推荐指数
1
解决办法
5275
查看次数

NSJSONSerialization,从IOS端看起来很好但在Rails 3服务器上没有转义

嗨,大家好所以我用NSJSONSerialization dataWithJSONObject:jsonDict选项:NSJSONWritingPrettyPrinted错误:零]命令写入JSON.它看起来很好,当我发布到Rails服务器时,"第一个名称"仍然存在.任何人都可以帮忙

NSArray *objects = [NSArray arrayWithObjects:@"firstname", @"lastname",nil];
NSArray *keys = [NSArray arrayWithObjects:@"dave", @"lu", nil];
NSDictionary *questionDict = [NSDictionary dictionaryWithObjects:keys forKeys:objects];


NSArray *objects2 = [NSArray arrayWithObjects:@"utf8", 
                                @"authenticity_token",@"check_i_ndatum", @"commit",nil];
NSArray *keys2 = [NSArray arrayWithObjects:@"1", @"xx",questionDict,@"Create Check i 
                                                                          Nadtum", nil];
NSDictionary *jsonDict = [NSDictionary dictionaryWithObjects:keys2 forKeys:objects2];

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict 
                                          options:NSJSONWritingPrettyPrinted error:nil];


NSURL * url =[NSURL URLWithString:@"http://192.168.1.105:3000/check_i_ndata"];
 //the request

NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url    
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
//bind req w/ json
[request setHTTPMethod:@"POST"];
//[request setValue:@"check_i_ndata" forHTTPHeaderField:@"Accept"];
[request setValue:[NSString stringWithFormat:@"%d",[jsonRequestData length]] 
forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:jsonRequestData]; …
Run Code Online (Sandbox Code Playgroud)

rest ruby-on-rails nsurlrequest ruby-on-rails-3 nsjsonserialization

0
推荐指数
1
解决办法
1145
查看次数

对于没有数据返回的网络摄像头,使用NSURLRequest + NSURLConnection似乎有点过分

所有,

这似乎非常简单,但我已经通过URL加载系统程序指南和各种NSURL ....类,但没有找到我的答案.

我只是想从应用程序到网站进行一个简单的电话预订派对点:

NSString *path=[NSString stringWithFormat:@"http://www.myparty123.com/ireservedURL.asp?Nickname=%@&Seat=%i&Email=%@&Currentparty=%i",john,5432,john@yahoo.com,6598];
NSURL* reservationURL =[NSURL URLWithString:path];
NSData *call= [NSData dataWithContentsOfURL:reservationURL];   
Run Code Online (Sandbox Code Playgroud)

这似乎是一个简单的方法,但我得到这个警告,我没有使用"调用"变量.使用NSData进行调用似乎有点过分,因为没有数据返回.

然而,创建NSURLRequest并启动NSURLConnection然后使用该请求实现委托似乎也是过度的.

我错过了什么

谢谢九巴

nsurlconnection nsdata nsurlrequest ios

0
推荐指数
1
解决办法
451
查看次数

NSURLResponse没有名为allHeaderFields的成员

我正在向API发出POST请求,我在Swift中成功获得了响应.以下是我的代码.

private func getData(url: NSURL) {
    let config: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session: NSURLSession = NSURLSession(configuration: config)

    let dataTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in

        if error {
            println("Error Occurred: \(error.localizedDescription)")
        } else {
            println("\(response.allHeaderFields)") // Error
        }
    })
    dataTask.resume()
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用转储头字段allHeaderFields但是我收到一个错误,说NSURLResponse没有名为allHeaderFields的成员.但确实有它!

语法或我调用它的方式一定有问题.谁能告诉我如何纠正这个问题?

谢谢.

post nsurlrequest http-headers ios swift

0
推荐指数
1
解决办法
2712
查看次数

NSURLRequest setHTTPBody readonly

NSURLRequest *r = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:path]];
[r setHTTPBody:imageData];
r.HTTPBody = imageData;
Run Code Online (Sandbox Code Playgroud)

Xcode在第二行给出错误: "No visible interface for 'NSURLRequest declares the selector 'setHTTPBody'"

和第三行 "Assignment to readonly property"

但是类定义显示了

/*! 
    @method HTTPBody:
    @abstract Sets the request body data of the receiver.
    @discussion This data is sent as the message body of the request, as
    in done in an HTTP POST request.
    @param data the new request body data for the receiver.
*/
@property (copy) NSData *HTTPBody;
Run Code Online (Sandbox Code Playgroud)

objective-c nsurlrequest

0
推荐指数
1
解决办法
165
查看次数

如何传递授权令牌标头目标c?

我正在传递用户名,API调用的密码返回正确的值。但是在身份验证API返回安全令牌后,我需要捕获令牌并传递用户名和密码。我在下面传递标头值的代码

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:[self HTTPMethod]];
[request setHTTPBody:self.requestData];
[request addValue:@"xyz" forHTTPHeaderField:@"username"];
[request addValue:@"xyz" forHTTPHeaderField:@"password"];
[request addValue:[[NSUserDefaults standardUserDefaults]valueForKey:@"Auth"] forHTTPHeaderField:@"Authorization"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
Run Code Online (Sandbox Code Playgroud)

我搜索了标头方法,但没有任何帮助。我在这里做错了什么。请任何人帮助我修复它。谢谢。

authorization objective-c nsurlrequest http-headers ios9.1

0
推荐指数
1
解决办法
3004
查看次数

API调用在swift中提供过时的响应

我正在swift中进行HTTP get请求,因为某些原因我得到了过时的响应.我已经将Postman中的响应与我在Xcode中打印的响应进行了比较,我得到了这个...

邮递员的回应标题:

邮差回复标题截图

在Xcode控制台中打印的响应标头:

Xcode控制台响应头截图

看到以绿色突出显示的部分,两个呼叫都是同时进行的.这是我项目的实时API,因为当前的实时数据没有变化,我没有显示JSON响应.但正如你在响应标题中看到的那样,Postman和Xcode中字段"Date"的值是不同的.当我在Postman中执行它时,它每次都给我新的响应.但是在Xcode中我整天都得到了相同的响应.我不知道为什么会这样.在擦除模拟器的内容(或从模拟器中删除应用程序)并重新安装项目后,它给了我一个新的更新响应.但它再次重复......

RequestManager类中的代码:

import Foundation

class RequestManager {

class func callTheGetAPI(urlString: String, closure: @escaping (Data?)->Void) {

    let url = URL.init(string: urlString)
    var urlRequest = URLRequest(url: url!)
    urlRequest.httpMethod = "GET"
    urlRequest.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in

        if (error != nil) {
            print(error!.localizedDescription)
        } else {
            let httpResponse = response as? HTTPURLResponse
            print(httpResponse!.allHeaderFields)
            closure(data)
        }
    }
    dataTask.resume()
  }
}
Run Code Online (Sandbox Code Playgroud)

我的ViewController中的代码:

 override func viewDidLoad() {
    super.viewDidLoad()
    getRecommendedData()
}

func getRecommendedData() {
    let …
Run Code Online (Sandbox Code Playgroud)

xcode nsurlrequest ios swift

0
推荐指数
1
解决办法
117
查看次数

检查 Internet 访问是否可用

在我的应用程序中,我只想在可以访问互联网的情况下拨打网络电话。

注意:我连接到没有互联网的 WiFi 点

我想测试互联网是否可用。我尝试使用这里描述的可达性,我也尝试了一个更简单的解决方案,如这里描述

问题在于 Reachability 会返回 Internet 可达的信息,而当它不可达时。另一种解决方案需要太多时间才能做出响应。我试图为请求和会话设置超时间隔,但它被忽略了。

如果我连接到没有互联网的 wifi,如何测试互联网可达性?

这是我使用的一些代码:

- (void) postAsyncTaskWithUrl:(NSString*)urlString
                      andType:(NSString*)requestType
                     andToken:(NSString*)token
          andPropertiesObject:(id)propObject
                   urlEncoded:(BOOL)isUrlEncoded
                  withSuccess:(nullable void(^)(id _Nullable))success
                   andFailure:(nullable void(^)(id _Nullable))failure
{

    internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];

    __weak typeof(self) weakSelf = self;
    // Internet is reachable
    internetReachableFoo.reachableBlock = ^(Reachability*reach)
    {
                 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:urlSt];
        [request setTimeoutInterval:20]; //Ignored ... WHY?

        NSURLSessionConfiguration *sessionConfigurations = [NSURLSessionConfiguration defaultSessionConfiguration];
        [sessionConfigurations setTimeoutIntervalForRequest:20]; //Ignored ... WHY?
        [sessionConfigurations setTimeoutIntervalForResource:20]; //Ignored ... WHY?
//        NSURLSession *session = [NSURLSession sharedSession]; …
Run Code Online (Sandbox Code Playgroud)

nsurlrequest reachability ios nsurlsession nsurlsessionconfiguration

0
推荐指数
1
解决办法
394
查看次数