问题描述:

I have tried to find this answer for days now and cant find anything. I store url to image in my database and Im trying to get this url and load the image to a ImageView.

Users uploads a image and my PHP script makes a url to the image in the database. This is my database table: ID -> Username -> Password -> urlImage. And I have another PHP script that takes the username and askes for the urlImage.

In Xcode i want to add this: `

NSUserDefaults *settings = [NSUserDefaults standardUserDefaults];

NSString *user = [settings valueForKey:@"username"];

NSString *post = [NSString stringWithFormat:@"username=%@&image=dummy",user];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:@"http://url.com/Wish_Profile_Pic.php"]];

NSString *postLen = [[NSString alloc] initWithFormat:@"%d" ,[post length ]];

[request setValue:postLen forHTTPHeaderField:@"Content-Length"];

[request setHTTPMethod:@"POST"];

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

//this is hard coded based on your suggested values, obviously you'd probably need to make this more dynamic based on your application's specific data to send

[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];

[[NSURLConnection alloc] initWithRequest:request delegate:self];

`

This will send a request to the database sever and the server will output the urlImage. How can I view the image in the ImageView? Cant find anything about this.

网友答案:
NSString *post = [NSString stringWithFormat:@"username=%@&image=dummy",use];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://url.com/Wish_Profile_Pic.php"]];
NSString *postLen = [[NSString alloc] initWithFormat:@"%d" ,[post length ]];
[request setValue:postLen forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *r, NSData *data, NSError *e) {
    if(data.length) {
        UIImage *img = [[[UIImage alloc] initWithData:data] autorelease];

        //try base64 
        if(!img) {
            //NEEDS http://projectswithlove.com/projects/NSData_Base64.zip
           id b64 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
           id data2 = [NSData dataFromBase64String:b64];
           img = [[[UIImage alloc] initWithData:data2] autorelease];
        }
        if(img)
            self.imageView.image = img;
    }
    else if(e)
        NSLog(@"%@", e);
}];
相关阅读:
Top